在自定义的SimpleCursorAdapter中使用getLayoutInflater

8

我卡在创建自定义适配器上了。我想在ListView内的按钮上设置setOnClickListener,并找到了这个看起来不错的主题 how-to-setonclicklistener-on-the-button-inside-the-listview 但问题是我在getLayoutInflater行上得到了无法访问的代码错误。

这是我的代码:

public class MyCursorAdapter extends SimpleCursorAdapter{

    private final Context ctx;
    private Button tagButton = null;

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        return super.getView(position, convertView, parent);
        LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View rowView = li.inflate(R.layout.tags_list_element, null, true);
        tagButton= (Button)rowView.findViewById(R.id.tag_title);
        tagButton.setTag(position);

        tagButton.setOnClickListener(new View.OnClickListener() {

            @Override
            public void onClick(View arg0) {
            }
        });
        return rowView;

    }

}

两种方法都对我不起作用。

  LayoutInflater inflater = context.getLayoutInflater();

而且
LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

请问您能否给我展示一下错误日志? - c2dm
2个回答

20

尝试:

View myView = LayoutInflater.from(ctx).inflate(R.layout.my_view, null);

此外,您收到了哪个异常?


编辑:在您的“getView”方法中,第一行是“return .....”,因此我认为您的方法的其余部分将永远不会执行....;)


我错过了开头的返回.. 谢谢 ;) - Greg

4

就性能而言:

View myView = LayoutInflater.from(context).inflate(R.layout.my_view, parent, false);

这是正确的做法;但更高效的方法是在适配器中将 inflater 存储在一个 final 字段中。

private final Context ctx;
private final LayoutInflater mInflater;
private Button tagButton = null;

public MyCursorAdapter(Context context, int layout, Cursor c,
          String[] from, int[] to) {
    super(context, layout, c, from, to);
    ctx = context;
    mInflater = LayoutInflater.from(ctx);
}

然后执行您的getView操作。

//....
final View v = mInflater.inflate(R.layout.list_item, parent, false);
//....
//stuff here
//
return v;

请确保您的Context是Activity Context,否则会出现主题问题。

祝好, Chris


网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接