NeilMonday
NeilMonday

Reputation: 2730

How to tell a View subclass to load its own layout

I have a custom View subclass which I am calling ListItem which has a layout (res/layout/list_item.xml). I cannot get my ListItem class to load the layout xml file.

public class ListItem extends View{

    private TextView title, subtitle;

    public ListItem(Context context) {
        this(context, null);
    }

    public ListItem(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public ListItem(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);

        //I want to load/inflate the view here so I can set title and subtitle.
    }
}

I can get the view to load by doing this, but I don't like the fact that it happens outside of the scope of the ListItem class. It seems like ListItem should be responsible for loading its own view. From ListViewAdapter.java:

public View getView(int position, View convertView, ViewGroup parent) {
    ListItem entry = items.get(position);
    if (convertView == null) {
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        convertView = inflater.inflate(R.layout.list_item, null);
    }

    TextView title = (TextView) convertView.findViewById(R.id.title);
    title.setText(entry.getTitle());

    TextView subtitle = (TextView) convertView.findViewById(R.id.subtitle);
    subtitle.setText(entry.getSubtitle());

    return convertView; 
}

Again, I want to load the layout from within the ListItem class. Is it possible for a view to load its own layout?

Upvotes: 0

Views: 319

Answers (2)

Seva Alekseyev
Seva Alekseyev

Reputation: 61378

You got it backwards. A view does not load a layout; a view is loaded from the layout. If you want the root element of the layout to be an instance of your view, use a custom view tag in the layout: <com.mypackage.ListItem>.

Upvotes: 1

John Boker
John Boker

Reputation: 83719

I usually do something like:

public ListItem(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View inflatedView = inflater.inflate(R.layout.list_item, this);

        TextView title = (TextView) inflatedView .findViewById(R.id.title);
        title.setText(entry.getTitle()); // entry needs to be available
        TextView subtitle = (TextView) inflatedView .findViewById(R.id.subtitle);
        subtitle.setText(entry.getSubtitle()); // entry needs to be available
    }

Upvotes: 0

Related Questions