I would like to add programmatically to LinearLayout some TextViews. And I want to use LayoutInflater. I have in my activity layout xml file:
<LinearLayout
android:id="@+id/linear_layout"
android:layout_width="wrap_content"
android:layout_height="fill_parent"
android:orientation="vertical"
/>
I have written in activity code like this below.
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.linear_layout);
LayoutInflater inflater = (LayoutInflater) getApplicationContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true);
textView.setText("Some text");
linearLayout.addView(textView);
My scale.xml file looks like:
<?xml version="1.0" encoding="utf-8"?>
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_marginLeft="50dp"
android:layout_marginRight="50dp"
android:drawableTop="@drawable/unit"
/>
At the line TextView textView = (TextView) inflater.inflate(R.layout.scale, linearLayout, true); I have fatal exception like this below.
java.lang.RuntimeException: Unable to start activity ComponentInfo{my.package/my.package.MyActivity}:
java.lang.ClassCastException: android.widget.LinearLayout
Caused by: java.lang.ClassCastException: android.widget.LinearLayout
When I replace in problematic line linearLayout with null I don’t have any exception, but the android:layout_marginLeft and android:layout_marginRight from my scale.xml are ignored and I can’t see any margins around added TextView.
I have found question Android: ClassCastException when adding a header view to ExpandableListView but in my case I have exception in first line in which I use the inflater.
When you specify the root view (
linearLayout) in the call toinflater.inflate(), the inflated view is automatically added to the view hierarchy. Consequently, you don’t need to calladdView. Also, as you noticed, the returned view is the root view of the hierarchy (aLinearLayout). To get a reference to theTextViewitself, you can then retrieve it with:If you were to give the view an
android:idattribute in scale.xml, you could retrieve it with