Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Get resource id from which view was inflated

Is there a way to obtain the resources id (like R.layout.viewtoInflate) of the layout from which a view was inflated?

I am trying to implement a List View that uses 2 custom layouts for the list items. Which item layout is used is based on a field in the objects used to populate the list view.

What I am missing in my custom adapter is a way to know what resource the 'convertView' I get in the getView() was inflated from. If I could get that info I can compare and determine whether I can re-use the convert view as it is or if I have to replace it with the appropriate layout for the current item.

So ideally it would be something like this:

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

    JSONObject currItem = mItems.getJSONObject(position);

    int layoutType;

    if (currItem.getBoolean("alternate"))
        layoutType = R.layout.list_item_b;
    else
        layoutType = R.layout.list_item_a;

    if (convertView == null || <convertView.resourceID> != layoutType ) {
        convertView = inflater.inflate(layoutType, null);

        //Finish setting up new View and its holder
    }
    else {
        //Get view holder for view reuse
    }

    //populate view with the required content

    return convertView;
}

At worst I could just not re-use views at all and just inflate the layout I need every time, but it seems very wasteful.

like image 809
RobertoCuba Avatar asked Apr 08 '13 20:04

RobertoCuba


1 Answers

There is an official way to use multiple layouts, simply override getViewTypeCount() and getItemViewType(). These methods inform the Adapter to expect multiple layouts and convertView will always be the appropriate layout (so don't need to check the resource id.) Please see this example for some sample code.

But if you want to find out which layout is which, simply check for a unique characteristic. For example you can use findViewById() on a View that only exists in one layout, then check whether it returns null or not.

like image 123
Sam Avatar answered Oct 13 '22 10:10

Sam