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.