向ArrayAdapter添加自定义复选框

时间:2016-10-26 10:17:15

标签: android listview android-arrayadapter

我正在使用SQLite数据库来保存我的记录,在返回它们时我正在使用此代码:

 mydb = new DBHelper(this);
 ArrayList array_list = mydb.getAllItems();
 ArrayAdapter arrayAdapter=new ArrayAdapter(this,android.R.layout.simple_list_item_1, array_list);
 mRecyclerview =(RecyclerView) findViewById(R.id.items_List);
 obj = (ListView)findViewById(R.id.listView1);
 obj.setAdapter(arrayAdapter);

但是这显示了一个正常的项目列表,我想在每一行显示一个CheckBox的列表。我尝试使用BaseAdapter并尝试RecyclerView,但它只是不起作用。有没有办法自定义simple_list_item_1?

2 个答案:

答案 0 :(得分:0)

你必须编写自己的适配器并在getView()方法中,膨胀你自己的视图并将数据传递给它:

MyAdapter.java

public class MyAdapter extends BaseAdapter {

private final ArrayList data;
private final TextView text;
private final CheckBox check;
private final LayoutInflater inflater;
private final Context context;

public MyAdapter(Context context, ArrayList data) {
    this.context = context;
    this.data = data;
    inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}

@Override
public int getCount() {
    return data.size();
}

@Override
public Object getItem(int position) {
    return data.get(position);
}

@Override
public long getItemId(int position) {
    return data.get(position).getId();
}

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

    if (convertView == null) {
        convertView = inflater.inflate(R.layout.my_item_layout, null, false);
    }

    text = (TextView) convertView.findViewById(R.id.text_view);
    text.setText(data.get(position));

    check = (CheckBox) convertView.findViewById(R.id.check_box);

    return convertView;

}

my_item_layout将是这样的:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="right"
    android:orientation="horizontal">

    <TextView
        android:id="@+id/text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

    <CheckBox
        android:id="@+id/check_list"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

使用此功能,您只需显示复选框....您无法保存或更改复选框数据

答案 1 :(得分:0)

您是否尝试过 CheckedTextview

<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/checkedTextView1"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:padding="5dp"
    android:gravity="center|left"
    android:textColor="@color/black_color"
    android:drawablePadding="5dp"
    android:checkMark="?android:attr/listChoiceIndicatorMultiple"
    android:textSize="12dp"

     />