首页 > 解决方案 > Android CheckedTextView setChecked 无法正常工作

问题描述

将数据填充到适配器类中的列表视图(每个项目)中

 // populate the data
 item.setText(megaItem.getName());
 item.setChecked(megaItem.getStatus());

允许在活动中使用多个复选框选择

 listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

问题:

问题 #1。如果,我use above line在 Activity 中的代码,那么我can check and uncheck all the items在 a 中list,但问题是,我can't see some of my items as checked默认情况下,正如我status true在代码中为他们提到的那样

问题2。如果,我don't use above line在 Activity 中的代码,那么我can see some of my items as checked默认情况下,正如我在代码中提到他们的状态为真,但问题是,我can't check and uncheck any other item,在list

xml:

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
        android:id="@+id/checkedTextView"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/CustomStyledRadioButton"
        android:drawableLeft="?android:attr/listChoiceIndicatorMultiple" />

来自适配器类的 getView()

@Override

public View getView(int position, View convertView, ViewGroup parent)
{
    //get the data for the item at this position
    MegaItem megaItem = getItem(position);

    //check if the view is being reused, otherwise inflate it
    if(convertView == null)
    {
        convertView = LayoutInflater.from(getContext()).inflate(R.layout.items_listview_layout,parent,false);
    }

    //get references to the UI elements to populate them
    item = (CheckedTextView) convertView.findViewById(R.id.checkedTextView);

    //populate the data
    item.setText(megaItem.getItemName());
    item.setChecked(megaItem.getStatus());

    //return the view to render on the screen
    return convertView;
}

标签: android

解决方案


试试这个。

selectAll = (CheckBox) findViewById(R.id.selectAll);
selectAll.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
toggleAll(selectAll.isChecked());
    }
});



private void toggleAll(Boolean check)
{
int size = yourListView.getCount();
for ( int i=0; i<size ; i++ ) {
View v = yourListView.getAdapter().getView(i, null, null);
CheckedTextView tv = (CheckedTextView) v.findViewById(R.id.eventName);
tv.setChecked(check);
 }
 }

并在 getView() 方法中。

public View getView(int position, View convertView, ViewGroup parent) {               
  CheckedTextView name = (CheckedTextView) view.findViewById(R.id.eventName);
       String[] result = item.split("/");                
  name.setText("txt");
  name.setChecked(true);
  return view;

推荐阅读