How to inflate a textview xml in my layout?

android, android-layout

Solution

// inflate text view
    TextView textView =  (TextView) getLayoutInflater().inflate(R.layout.customtextview, null);

// add it to your view
// in your condition, we will add it to Linear Layout
  LinearLayout main = (LinearLayout)findViewById(R.id.mainView);
  main.addView(textView);

Problem

I have created a custom textview class and i am trying to inflate it in my main xml. Here is my code :- ``` public class CustomTextView extends TextView{ public CustomTextView(Context context) { super(context); LayoutInflater li = LayoutInflater.from(context); TextView view = (TextView) li.inflate(R.layout.customtextview,null); view.setBackgroundColor(Color.RED); } ``` } customtextview.xml ``` <?xml version="1.0" encoding="utf-8"?> <TextView xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:text="sgfiughbjkh" android:id="@+id/customtext" android:layout_height="match_parent" > </TextView> ``` and in my main activity xml, i have only one linear layout :- ``` LinearLayout main = (LinearLayout)findViewById(R.id.mainView); CustomTextView cus = new CustomTextView(this); main.addView(cus); ``` I know if i extend it to linear layout instead of textview and add a lienarlayout as parent and in it that textview, it works. But the problem is that i want to inflate an xml with only a textview and inflate it and the above code is not working. Please suggest How do inflate a xml containing only one textview using layout inflator ?

Original source