Android自定义适配器

时间:2012-01-31 15:22:17

标签: android database

我想创建一个自定义适配器,以便在每个列表项中都有一个可点击按钮。 我的问题是我从数据库获取数据,我不知道如何使用我的自定义适配器在列表中显示它们。这是我的适配器代码:

public class Adapter extends SimpleCursorAdapter {
    private Context mContext;

    final Drawable delete;
    private ImageButton imageButton2;

    private LayoutInflater inflater;

    private int favoriteListRow;

    public Adapter(Context ctx, int favoriteListRow, Cursor cursor,
            String[] columns, int[] to) {
        super(ctx, favoriteListRow, cursor, columns, to);

        mContext = ctx;
        inflater = LayoutInflater.from(mContext);

        delete_btn = ctx.getResources().getDrawable(R.drawable.delete);

        DB entry = new DB(ctx);
        entry.open();
        cursor = entry.getData();
        columns = new String[] { DBHelper.NAME, DBHelper.NAME2 };
        to = new int[] { R.id.textView01, R.id.textView02 };
        entry.close();

    }

    public View getView(Context context, Cursor cursor, ViewGroup parent) {

        final LayoutInflater inflater = LayoutInflater.from(mContext);

        View v = inflater.inflate(R.layout.row, parent, false);

        TextView name_text = (TextView) v.findViewById(R.id.textView01);

        int nameCol = cursor.getColumnIndex(DBHelper.NAME);

        String name = cursor.getString(nameCol);
        name_text.setText(name);

        TextView name2_text = (TextView) v.findViewById(R.id.textView02);
        int theCol = cursor.getColumnIndex(DBHelper.NAME2);

        String the = cursor.getString(theCol);
        the_text.setText(the);

        imageButton2 = (ImageButton) v.findViewById(R.id.delete_btn);
        imageButton2.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub

                Toast.makeText(mContext, "Button pressed", Toast.LENGTH_LONG)
                        .show();

            }
        });

        return v;
    }



}

然后从我的主要活动中调用适配器:

Adapter adapter;

ListView list = (ListView) findViewById(R.id.list);

        list.setAdapter(adapter);

1 个答案:

答案 0 :(得分:0)

尝试使用此行初始化Layout Inflater

LayoutInflater inflater = (LayoutInflater)context.getSystemService
  (Context.LAYOUT_INFLATER_SERVICE);