C#Listview中如何显示复选框

Posted

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了C#Listview中如何显示复选框相关的知识,希望对你有一定的参考价值。

参考技术A

在Winform中直接通过CheckBoxes属性设置

在WPF中修改列模板即可:

        <ListView Height="162" Canvas.Left="345" Canvas.Top="85" Width="143" >
            <ListView.View>
                <GridView>
                    <GridViewColumn>
                        <GridViewColumn.CellTemplate>
                            <DataTemplate>
                                <CheckBox />
                            </DataTemplate>
                        </GridViewColumn.CellTemplate>
                    </GridViewColumn>
                </GridView>
            </ListView.View>
        </ListView>

参考技术B ListView.CheckBoxes=true; 参考技术C 一、ListView类
1、常用的基本属性:
(1)FullRowSelect:设置是否行选择模式。(默认为false) 提示:只有在Details视图该属性才有意义。
(2) GridLines:设置行和列之间是否显示网格线。(默认为false)提示:只有在Details视图该属性才有意义。
(3)AllowColumnReorder:设置是否可拖动列标头来对改变列的顺序。(默认为false)提示:只有在Details视图该属性才有意义。

(4)View:获取或设置项在控件中的显示方式,包括Details、LargeIcon、List、SmallIcon、Tile(默认为 LargeIcon)

(5)MultiSelect:设置是否可以选择多个项。(默认为false)
(6)HeaderStyle:获取或设置列标头样式。
Clickable:列标头的作用类似于按钮,单击时可以执行操作(例如排序)。
NonClickable:列标头不响应鼠标单击。
None:不显示列标头。

(7)LabelEdit:设置用户是否可以编辑控件中项的标签,对于Detail视图,只能编辑行第一列的内容。(默认为false)
(8)CheckBoxes:设置控件中各项的旁边是否显示复选框。(默认为false)
(9)LargeImageList:大图标集。提示:只在LargeIcon视图使用。
(10)SmallImageList:小图标集。提示:只有在SmallIcon视图使用。
(11)StateImageList:图像蒙板。这些图像蒙板可用作LargeImageList和SmallImageList图像的覆盖图,这些图像可用于指示项的应用程序定义的状态。(暂时不大懂)

(12)SelectedItems:获取在控件中选定的项。
(13)CheckedItems:获取控件中当前复选框选中的项。
(14)Soritng:对列表视图的项进行排序。(默认为None)
Ascending:项按递增顺序排序。
Descending:项按递减顺序排序。
None:项未排序。
(15)Scrollable:设置当没有足够空间来显示所有项时是否显示滚动条。(默认为true)
(16)HoverSelection:设置当鼠标指针悬停于项上时是否自动选择项。(默认为false)
(17)HotTracking:设置当鼠标指针经过项文本时,其外观是否变为超链接的形式。(默认为false)

(18)HideSelection:设置选定项在控件没焦点时是否仍突出显示。(默认为false)
(19)ShowGroups:设置是否以分组方式显示项。(默认为false);
(20)Groups:设置分组的对象集合。
(21)TopItem:获取或设置控件中的第一个可见项,可用于定位。(效果类似于EnsureVisible方法)

2、常用方法:
(1)BeginUpdate:避免在调用EndUpdate 方法之前描述控件。当插入大量数据时,可以有效地避免控件闪烁,并能大大提高速度。
(2)EndUpdate:在BeginUpdate 方法挂起描述后,继续描述列表视图控件。(结束更新)
(3)EnsureVisible:列表视图滚动定位到指定索引项的选项行。(效果类似于TopItem属性)
(4)FindItemWithText:查找以给定文本值开头的第一个 ListViewItem。
(5)FindNearestItem:按照指定的搜索方向,从给定点开始查找下一个项。提示:只有在LargeIcon或SmallIcon视图才能使用该方法。

3、常用事件:
(1)AfterLabelEdit:当用户编辑完项的标签时发生,需要LabelEdit属性为true。
(2)BeforeLabelEdit:当用户开始编辑项的标签时发生。
(3)ColumnClick:当用户在列表视图控件中单击列标头时发生。
参考技术D 用模板?是这样吧

如何使用复选框和自定义适配器从 Listview 中获取选定的列表项?

【中文标题】如何使用复选框和自定义适配器从 Listview 中获取选定的列表项?【英文标题】:How to get selected list items from a Listview with checkBox and Custom Adapter? 【发布时间】:2012-06-10 07:12:29 【问题描述】:

我有一个ListView,上面有CheckBox。我正在使用Custom Adapter 填充ListView

在我的xml 文件中,底部有一个Button。我想要的是让用户在ListView 中选择行数,当他/她点击Button 时,获取所选项目的位置,以便我可以获取特定行的对象以进行进一步计算。

【问题讨论】:

***.com/questions/10895763/… 【参考方案1】:

Below Snippet 完全符合您的要求。

package com.windrealm.android;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class PlanetsActivity extends Activity


    private ListView mainListView;
    private Planet[] planets;
    private ArrayAdapter<Planet> listAdapter;
    private Button check;
    private Context context;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState)
    
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        context = PlanetsActivity.this;
        check = (Button) findViewById(R.id.check);
        // Find the ListView resource.
        mainListView = (ListView) findViewById(R.id.mainListView);

        // When item is tapped, toggle checked properties of CheckBox and
        // Planet.
        mainListView
                .setOnItemClickListener(new AdapterView.OnItemClickListener()
                
                    @Override
                    public void onItemClick(AdapterView<?> parent, View item,
                            int position, long id)
                    
                        Planet planet = listAdapter.getItem(position);
                        planet.toggleChecked();
                        PlanetViewHolder viewHolder = (PlanetViewHolder) item
                                .getTag();
                        viewHolder.getCheckBox().setChecked(planet.isChecked());
                    
                );

        // Create and populate planets.
        planets = (Planet[]) getLastNonConfigurationInstance();
        if (planets == null)
        
            planets = new Planet[]
             new Planet("Mercury"), new Planet("Venus"), new Planet("Earth"),
                    new Planet("Mars"), new Planet("Jupiter"),
                    new Planet("Saturn"), new Planet("Uranus"),
                    new Planet("Neptune"), new Planet("Ceres"),
                    new Planet("Pluto"), new Planet("Haumea"),
                    new Planet("Makemake"), new Planet("Eris") ;
        
        ArrayList<Planet> planetList = new ArrayList<Planet>();
        planetList.addAll(Arrays.asList(planets));

        // Set our custom array adapter as the ListView's adapter.
        listAdapter = new PlanetArrayAdapter(this, planetList);
        mainListView.setAdapter(listAdapter);

        check.setOnClickListener(new OnClickListener()
        

            @Override
            public void onClick(View view)
            
                for (int i = 0; i < listAdapter.getCount(); i++)
                
                    Planet planet = listAdapter.getItem(i);
                    if (planet.isChecked())
                    
                        Toast.makeText(context,
                                planet.getName() + " is Checked!!",
                                Toast.LENGTH_SHORT).show();
                    
                

            
        );
    

    /** Holds planet data. */
    private static class Planet
    
        private String name = "";
        private boolean checked = false;

        public Planet()
        
        

        public Planet(String name)
        
            this.name = name;
        

        public Planet(String name, boolean checked)
        
            this.name = name;
            this.checked = checked;
        

        public String getName()
        
            return name;
        

        public void setName(String name)
        
            this.name = name;
        

        public boolean isChecked()
        
            return checked;
        

        public void setChecked(boolean checked)
        
            this.checked = checked;
        

        public String toString()
        
            return name;
        

        public void toggleChecked()
        
            checked = !checked;
        
    

    /** Holds child views for one row. */
    private static class PlanetViewHolder
    
        private CheckBox checkBox;
        private TextView textView;

        public PlanetViewHolder()
        
        

        public PlanetViewHolder(TextView textView, CheckBox checkBox)
        
            this.checkBox = checkBox;
            this.textView = textView;
        

        public CheckBox getCheckBox()
        
            return checkBox;
        

        public void setCheckBox(CheckBox checkBox)
        
            this.checkBox = checkBox;
        

        public TextView getTextView()
        
            return textView;
        

        public void setTextView(TextView textView)
        
            this.textView = textView;
        
    

    /** Custom adapter for displaying an array of Planet objects. */
    private static class PlanetArrayAdapter extends ArrayAdapter<Planet>
    

        private LayoutInflater inflater;

        public PlanetArrayAdapter(Context context, List<Planet> planetList)
        
            super(context, R.layout.simplerow, R.id.rowTextView, planetList);
            // Cache the LayoutInflate to avoid asking for a new one each time.
            inflater = LayoutInflater.from(context);
        

        @Override
        public View getView(int position, View convertView, ViewGroup parent)
        
            // Planet to display
            Planet planet = (Planet) this.getItem(position);

            // The child views in each row.
            CheckBox checkBox;
            TextView textView;

            // Create a new row view
            if (convertView == null)
            
                convertView = inflater.inflate(R.layout.simplerow, null);

                // Find the child views.
                textView = (TextView) convertView
                        .findViewById(R.id.rowTextView);
                checkBox = (CheckBox) convertView.findViewById(R.id.CheckBox01);

                // Optimization: Tag the row with it's child views, so we don't
                // have to
                // call findViewById() later when we reuse the row.
                convertView.setTag(new PlanetViewHolder(textView, checkBox));

                // If CheckBox is toggled, update the planet it is tagged with.
                checkBox.setOnClickListener(new View.OnClickListener()
                
                    public void onClick(View v)
                    
                        CheckBox cb = (CheckBox) v;
                        Planet planet = (Planet) cb.getTag();
                        planet.setChecked(cb.isChecked());
                    
                );
            
            // Reuse existing row view
            else
            
                // Because we use a ViewHolder, we avoid having to call
                // findViewById().
                PlanetViewHolder viewHolder = (PlanetViewHolder) convertView
                        .getTag();
                checkBox = viewHolder.getCheckBox();
                textView = viewHolder.getTextView();
            

            // Tag the CheckBox with the Planet it is displaying, so that we can
            // access the planet in onClick() when the CheckBox is toggled.
            checkBox.setTag(planet);

            // Display planet data
            checkBox.setChecked(planet.isChecked());
            textView.setText(planet.getName());

            return convertView;
        

    

    public Object onRetainNonConfigurationInstance()
    
        return planets;
    

【讨论】:

【参考方案2】:

要解决这个问题,您必须创建一个自定义 Item 类,该类将代表您在列表中的各个复选框。然后适配器类将使用这些项目的数组来显示您的复选框。

这个 Item 类将有一个布尔变量 isSelected,它将确定复选框是否被选中。您必须在自定义适配器类的 OnClick 方法中设置此变量的值

举例

    class CheckBoxItem

    boolean isSelected;


    public void setSelected(boolean val) 
            this.isSelected = val;
        

        boolean isSelected()
            return isSelected;

           

    

对于您的 CustomAdapter 类,如下所示:

    public class ItemsAdapter extends ArrayAdapter implements OnClickListener  

// you will have to initialize below in the constructor 
    CheckBoxItem items[];



    // You will have to create your check boxes here and set the position of your check box
    /// with help of setTag method of View as defined in below method, you will use this later // in your onClick method 

    @Override 
        public View getView(int position, View convertView, ViewGroup parent)  
            View v = convertView; 



            CheckBox cBox = null;

            if (v == null)  
                LayoutInflater vi = (LayoutInflater) apUI.getSystemService(Context.LAYOUT_INFLATER_SERVICE); 
                v = vi.inflate(R.layout.attachphoto, null);     

             



            CheckBoxItemItem it = items[position];      

            cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
            cBox.setOnClickListener(this);
            cBox.setTag(""+position);       


            Log.d(TAG, "  CHECK BOX IS: "+cBox+ "   Check Box selected Value: "+cBox.isChecked()+"  Selection: "+it.isSelected());
            if(cBox != null)
                cBox.setText("");
                cBox.setChecked(it.isSelected());
                   


            return v; 
         


        public void onClick(View v) 
            CheckBox cBox =(CheckBox) v.findViewById(R.id.apCheckBox);
            int position = Integer.parseInt((String) v.getTag());

            Log.d(TAG, "CLicked ..."+cBox.isChecked());

            items[position].setSelected(cBox.isChecked());              
         

    

稍后您将声明 CheckBoxItem 类的数组,该类将包含在您的 Adapter 类中,在这种情况下,它将是 ItemsAdapter 类。

然后当用户按下按钮时,您可以遍历数组中的所有项,并使用 CheckBoxItem 类的 isSelected() 方法检查选择了哪一项。

在您的活动中,您将拥有:

ArrayList getSelectedItems()

ArrayList selectedItems = new ArrayList();

int size = items.length;

        for(int i = 0; i<size; i++)
            CheckBoxItem cItem = items[i];
            if(cItem.isSelected())                 
                selectedItems.add(cItem);                   
                       
        

return selectedItems;


【讨论】:

【参考方案3】:

我遇到了完全相同的问题。我是这样解决的

public class myActivity extends Activity  
//ActionBarSherlock mSherlock = ActionBarSherlock.wrap(this);
public ListView listview;
private ArrayList<Object> itemlist=new ArrayList<Object>();
Button button;
private myAdapter adapter;

@Override
public void onCreate(Bundle savedInstanceState) 
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    listview=(ListView)findViewById(R.id.listview1);
    button=(Button)findViewById(R.id.button1);
    /*add some data to ur list*/ itemlist.add(something);
    adapter=new Adapter(myActivity.this, 0, itemlist);
    listview.setAdapter(adapter);
    **listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
    listview.setItemsCanFocus(false);**
    button.setOnClickListner(new OnClickListner()
    
     @Override
     public void OnClick(View v)
     
      /* this returns the checked item positions in the listview*/
      **ArrayList<Integer> itempositions=adapter.getcheckeditemcount();**

    for(int i:itempositions)
    
             /* This is the main part...u can retrieve the object in the listview which is checked and do further calculations with it*/
        **Object info=adapter.getItem(i);**
                          Log.d(TAG,"checked object info= ",info.something);
                 
     
    );



private class myAdapter extends ArrayAdapter<Object>  

    private Context context;
    private ArrayList<Object> list;
    **private ArrayList<Integer> checkedpositions;**


    public myAdapter(Context localContext,int textViewResourceId, ArrayList<Object> objects) 
        super(localContext,textViewResourceId,objects);
        context = localContext;
        this.list=objects;
        this.checkedpositions=new  ArrayList<Integer>();
        //Log.d("adapter","list size= "+objects.size());
    

@Override       
    public View getView(int position, View convertView, ViewGroup parent) 

        ImageView picturesView;
        View v = convertView;
        TextView Mainitem;
        final CheckBox check;

       if (v == null) 
       
           LayoutInflater vi = (LayoutInflater)getSystemService(Context.LAYOUT_INFLATER_SERVICE);
           v = vi.inflate(R.layout.albumview, null);


           Object item=list.get(position);
           if(item!=null)
           

               check = (CheckBox)v.findViewById(R.id.checkBox1);
                   /* set a tag for chekbox with the current view position */
               **check.setTag(position);**
                   /*set a onchecked change listner for listning to state of checkbox toggle */
               check.setOnCheckedChangeListener(new OnCheckedChangeListener() 
                
                   @Override
                   public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) 
                                
                                       /*get the tag of the checkbox...in this case this will give the (position of view)*/
                       Object tag=check.getTag();
                       if ( isChecked ) 
                        
                           // perform logic 
                           count++;
                           Log.d("Checkbox","added "+tag);
                           checkedpositions.add((Integer) tag);
                        
                       else
                       
                           count--;
                           checkedpositions.remove(tag);
                           Log.d("Checkbox","removed "+(Integer)tag);
                       

               /* if u dont have a textview in ur listview then ignore this part */        
               Mainitem = (TextView) v.findViewById(R.id.textView1);
               Mainitem.setText(item.Album_name);

                catch (IOException e) 
                     // TODO Auto-generated catch block
                     Log.d("error", "wall");
                 

           

       

    return v;

    
   /* Finally create a method which return the checkeditem postions in the listview */
**public ArrayList<Integer> getcheckeditemcount()

    return this.checkedpositions;
**




我希望这会有所帮助。

【讨论】:

【参考方案4】:

在customadapter的getview方法中,做

//use the actual id of your checkbox of course
Checkbox checkbox = (CheckBox)findViewById(R.id.checkbox); 
checkbox.setFocusable(false);
checkbox.setFocusableInTouchMode(false);

现在复选框和列表项一样可以点击。

【讨论】:

以上是关于C#Listview中如何显示复选框的主要内容,如果未能解决你的问题,请参考以下文章

Winform中ListView 的view 属性设置为SmallIcon时最左边的复选框会显示不全(会被盖住半块)?

Flutter Listview语言选择需要在选择时进行圆形复选框设计

单击按钮时如何在android中获取带有ListView值的复选框,EditText?

Listview和复选框(如何放入数据库(sqlite))

制作带复选框的ListView控件

如何使用 ListView 构建器在一行中显示 CheckboxListTile 文本?