Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

getLayoutInflater inside custom simpleCursorAdapter

I'm stuck with creating custom adapter. I want to setOnClickListener on the buttons inside ListView and I found this topic which looks ok how-to-setonclicklistener-on-the-button-inside-the-listview but the problem is that I'm getting unreachable code error on the getLayoutInflater line.

here is my code

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;

    }

}

both methods doesn't work for me

  LayoutInflater inflater = context.getLayoutInflater();

and

LayoutInflater li = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
like image 835
Greg Avatar asked May 21 '12 12:05

Greg


2 Answers

Try:

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

Moreover, what exception do you get?


Edit: In your "getView" method, the first line is "return.....", so the rest of your method won't ever be executed, I think.... ;)

like image 178
Jeje Doudou Avatar answered Oct 04 '22 09:10

Jeje Doudou


From a performance point of view:

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

Is correct; but its more efficient to store the inflater in an final field inside the adapter.

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);
}

Then do your getView operation.

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

ALSO make sure you Context is your Activity Context, you will get Theming issues if you use the wrong context.

Regards, Chris

like image 44
Chris.Jenkins Avatar answered Oct 04 '22 08:10

Chris.Jenkins