ListView带有文本和复选框

时间:2018-04-07 14:37:06

标签: android listview checkbox

我使用RelativeLayout作为我的ListView。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
android:padding="6dip" >

<CheckBox
    android:id="@+id/checkBox1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentLeft="true"
    android:focusable="false"
    android:focusableInTouchMode="false"
    android:text="CheckBox" />

<TextView
    android:id="@+id/test"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignBaseline="@+id/checkBox1"
    android:layout_alignBottom="@+id/checkBox1"
    android:layout_toRightOf="@+id/checkBox1"
    android:text="TextView" />

</RelativeLayout>

这是我的ListView代码,

private void displayList(){
    ArrayList<String> diyListArray = new ArrayList<String>();
    diyListArray.add("1");
    diyListArray.add("2");
    diyListArray.add("3");
    diyListArray.add("4");
    diyListArray.add("5");
    diyListArray.add("6");
    diyListArray.add("7");
    listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, R.id.test, diyListArray);
    diyList.setAdapter( listAdapter );
}

我们在这里可以看到我使用了具有TextView资源ID的ArrayAdapter。 我可以显示复选框及其相应的文本。

如何从复选框中获取用户选择的文本?

3 个答案:

答案 0 :(得分:0)

首先选择模式

listview.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);

我点击它来制作一个按钮,你可以检索你检查的所有项目

button.setOnClickListener(this);

@Override
public void onClick(View v) {

    SparseBooleanArray checked = listview.getCheckedItemPositions();

    ArrayList<String> selectedItems = new ArrayList<String>();

    for (int i = 0; i < checked.size(); i++) {
        int position = checked.keyAt(i);
        if (checked.valueAt(i))
            selectedItems.add(listAdapter.getItem(position));
    }
}

在这里,您将获得selectedItems ArrayList中检查的所有项目。

答案 1 :(得分:0)

尝试以下方法:

Demo10.class:----

public class Demo10 extends AppCompatActivity implements Listener {

private ListView lv;
private boolean[] state_ = new boolean[4];
private String[] text_ = new String[4];


@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.demo11);

    for(int i = 0 ; i<4 ; i++) {
        state_[i] =  false;
        text_[i] = "text"+i;
    }

    lv = (ListView) findViewById(R.id.lv);
    lv.setAdapter(new ItemAdapter(Demo10.this , this));// This includes a Listener that listens to onCheckBoxStateChanges.

    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() { // used to handle ListView onItemClicks and how they should affect the corresponding checkBox
        @Override
        public void onItemClick(AdapterView<?> parent, View view, int position, long id) {

            CheckBox cb = view.findViewById(R.id.cb);
            cb.setChecked(!cb.isChecked());
            displayCheckBoxStateText();
        }
    });

}


private void displayCheckBoxStateText(){


    for(int i = 0 ; i<4 ; i++){
        Log.e("CheckBox", text_[i]+" : " + state_[i]);
    }
}

@Override
public void checkBox1(boolean state) {
    state_[0] =  state;
    displayCheckBoxStateText();

}

@Override
public void checkBox2(boolean state) {
    state_[1] = state;
    displayCheckBoxStateText();

}

@Override
public void checkBox3(boolean state) {
    state_[2] = state;
    displayCheckBoxStateText();

}

@Override
public void checkBox4(boolean state) {
    state_[3] = state;
    displayCheckBoxStateText();

}
}

ItemAdapter.class:-----

public class ItemAdapter extends BaseAdapter {
private Context mContext;
private LayoutInflater layoutInflater;
private Listener callback;

public ItemAdapter(Context c , Listener l) {
    mContext = c;
    callback = l;
    layoutInflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

}

public int getCount() {
    return s.length;
}

public Object getItem(int position) {
    return null;
}

public long getItemId(int position) {
    return position;
}

public View getView(final int position, View convertView, ViewGroup parent) {
    CheckBox cb;
    View view = convertView;
    if (convertView == null) {
        if (layoutInflater != null) {
            view = layoutInflater.inflate(R.layout.demo10, null);
        }
    }
    cb = view.findViewById(R.id.cb);

    cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
            switch (position) {
                case 0:
                    callback.checkBox1(isChecked);
                    break;
                case 1:
                    callback.checkBox2(isChecked);
                    break;
                case 2:
                    callback.checkBox3(isChecked);
                    break;
                case 3:
                    callback.checkBox4(isChecked);
                    break;
                default:
                    break;
            }
        }
    });
    cb.setText(s[position]);
    return view;
}

private String[] s = {
        "test1",
        "test2",
        "test3",
        "test4"
};

}

监听器界面:----

public interface Listener {

public void checkBox1(boolean state);

public void checkBox2(boolean state);

public void checkBox3(boolean state);

public void checkBox4(boolean state);

}

demo10.xml:----

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:padding="6dip" >

    <CheckBox
        android:id="@+id/cb"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_alignParentLeft="true"
        android:focusable="false"
        android:focusableInTouchMode="false"
        android:text="" />

</RelativeLayout>

demo11.xml:-----

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent"
android:layout_height="match_parent">

<ListView
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/lv">
</ListView>

</android.support.constraint.ConstraintLayout>

答案 2 :(得分:0)

您可以覆盖ArrayAdapter的getView()并自己处理视图。替换:

listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, R.id.test, diyListArray);

    listAdapter = new ArrayAdapter<String>(this, R.layout.selectrow, diyListArray){
        boolean[] checked = new boolean[diyListArray.size()];
        @NonNull
        @Override
        public View getView(final int position, @Nullable View convertView, @NonNull ViewGroup parent) {
            if(convertView == null) convertView = getLayoutInflater().inflate(R.layout.selectrow, null);
            TextView textView = convertView.findViewById(R.id.test);
            CheckBox checkBox = convertView.findViewById(R.id.checkBox1);
            textView.setText(getItem(position));
            checkBox.setChecked(checked[position]);
            checkBox.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    checked[position] = !checked[position];
                    String msg = "Checked Item: ";
                    if(!checked[position]) msg = "Unchecked Item: ";
                    Toast.makeText(getContext(), msg + getItem(position), Toast.LENGTH_SHORT).show();
                    notifyDataSetChanged();
                }
            });
            return convertView;
        }
    };

我有关于ListView的博客:http://programandroidlistview.blogspot.com/

希望有所帮助!