jjz
jjz

Reputation: 2057

Difference between LayoutInflater and getLayoutInflater

I'm just wondering what's the difference between

(RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.todo_item, null);

and

(RelativeLayout) ((Activity)mContext).getLayoutInflater().inflate(R.layout.todo_item, null);

Here is how I am using it:

public class SomeAdapter extends BaseAdapter {

    private final List<ItemEntry> mItems = new ArrayList<ItemEntry>();
    private final Context mContext;

    public SomeAdapter(Context context) {
        mContext = context;
    }

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

        // TODO - Get the current ItemEntry
        final ItemEntry toDoItem = mItems.get(position);


        RelativeLayout itemLayout = null;
        // I'm getting ClassCastException on this.
        // itemLayout = (RelativeLayout) ((Activity) mContext).getLayoutInflater().inflate(R.layout.item_entry, null);

        // code run as expected
        itemLayout = (RelativeLayout) LayoutInflater.from(mContext).inflate(R.layout.item_entry, null);


        // more codes 
    }
}

Upvotes: 0

Views: 694

Answers (1)

CommonsWare
CommonsWare

Reputation: 1006624

getLayoutInflater(), where it is available, will always give you a LayoutInflater that takes themes and other styles into account.

LayoutInflater.from() just gives you a LayoutInflater, one that may or may not take themes and other styles into account, particularly depending upon what the Context is that you pass in as a parameter.

Outside of instrumentation testing and certain unusual scenarios (e.g., a Service needing to inflate a layout), use getLayoutInflater() for inflating layouts.

Upvotes: 1

Related Questions