如何为具有按钮等的列表项创建自定义适配器。*简单方法*

时间:2012-12-26 12:46:51

标签: android sqlite listview simplecursoradapter custom-adapter

我遇到了很多回答这个问题的问题,但是在我发现可扩展的问题上没有完全构建类,很多时候它会覆盖函数,特别是当我使用SimpleCursorAdapter时而不是BaseAdapter自动将SQLite数据填充到列表项中getView

我的答案中提供的代码是为了向您展示如何开发ListAdapter,它将添加可以处理点击事件的按钮,无需在列表项上启用点击事件或没有完全覆盖原始绘图你们延伸的课程。

1 个答案:

答案 0 :(得分:0)

首先是行的XML,如果要对其进行任何更改,则只需要在代码中更新4按钮的ID,其余部分不需要自定义部分:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_height="wrap_content" android:id="@+id/tag_row_layout"
     android:orientation="horizontal" android:layout_width="wrap_content">

     <TextView android:layout_width="wrap_content"
          android:layout_height="fill_parent" android:id="@+id/name"
          />
     <Button
          android:id="@+id/delete_button"
          android:layout_width="wrap_content" 
          android:layout_height="fill_parent" 
          android:text="Do Stuff"
          />
</LinearLayout>

这是一个非常简单的列表视图,使用LinearLayout它只会显示文本旁边的按钮,这没什么了不起。

接下来的部分就是让这个适配器的代码......

public class CustomListAdapter extends SimpleCursorAdapter {

    public CustomListAdapter(Context context, int layout, Cursor c, String[] from, int[] to) {
        super(context, layout, c, from, to);
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        convertView = super.getView(position, convertView, parent);

        Button btn = (Button)convertView.findViewById(R.id.delete_button);
        btn.setOnClickListener(new DeleteButton());

        return convertView;
    }

    protected final static class DeleteButton implements OnClickListener {
        public void onClick(View v) {
            Log.e("TestButton", "It's been fired!!!");
        }
    }
}

然后,您可以将此扩展到多个按钮,但在列表项XML中创建更多按钮,然后在static class中创建另一个CustomListAdapter。这非常适合扩展SimpleCursorAdapter,因为它仍然会将正确的数据注入正确的文本视图中。