android – How to create a custom View's layout programmatically?-ThrowExceptions

Exception or error:

In an Activity, you can create a LinearLayout programmatically in the following way:

public void onCreate(Bundle savedInstanceState) {

    LinearLayout ll = new LinearLayout(this);
    ll.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

    TextView tv1 = new TextView(this);

    TextView tv2 = new TextView(this);


How do you do the same inside a custom View subclass? There are no setContentView or onCreate methods…

How to solve:

Okay, I discovered one way of doing it. Basically, instead of subclassing the View class directly, you need to subclass the top-most class that you would normally define in XML. For example, if your custom View needs a LinearLayout as its top-most class, then your custom View should simply subclass LinearLayout.

For example:

public class MyCustomView extends LinearLayout
    public MyCustomView(Context context, AttributeSet attrs)
        super(context, attrs);

        setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));

        TextView tv1 = new TextView(context);

        TextView tv2 = new TextView(context);

Is subclassing LinearLayout a “hack”? Not as far as I can see. Some official View subclasses do the same, like NumberPicker and SearchView (even though they inflate their layouts from XML).

Upon reflection, it’s actually a pretty obvious answer.


If I understand your question, you need to use inflate, like this:

public final class ViewHolder {
        public TextView title;
        public TextView artist;
        public TextView duration;
        public ImageView thumb_image;
    //A class for the ViewHolder


// Put this where you want to inflate this layout, could be a customlistview
View view = getLayoutInflater().inflate(R.layout.your_layout, null);
holder = new ViewHolder();
    holder.title = (TextView)view.findViewById(; // title
    holder.artist = (TextView)view.findViewById(; // artist name
    holder.duration = (TextView)view.findViewById(; // duration
    holder.thumb_image=(ImageView)view.findViewById(; // thumb image

Leave a Reply

Your email address will not be published. Required fields are marked *