The problem here I don't get the same output view result in these two cases, I want to fix case 1 to get same output result as case 2:
Code and Output For Case 1:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
</LinearLayout>
text_view.xml
<?xml version="1.0" encoding="utf-8"?>
<TextView
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:textColor="#000000"
    android:text="1"
    android:textSize="20sp"
    android:background="#AAAAAA"
    android:gravity="center"
    android:layout_width="50dp"
    android:layout_height="50dp"
    android:layout_marginTop="2dp"
    android:layout_marginRight="2dp"
 />
onCreate method in LayoutTestActivity.java
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    LinearLayout lt = (LinearLayout) getLayoutInflater().inflate(R.layout.main, null);
    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.text_view, null);
    lt.addView(tv);
    setContentView(lt);
}
output view (Not Correct)

Code and Output For Case 2:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content">
    <TextView
        android:textColor="#000000"
        android:text="1"
        android:textSize="20sp"
        android:background="#AAAAAA"
        android:gravity="center"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginTop="2dp"
        android:layout_marginRight="2dp"
     />
</LinearLayout>
onCreate method in LayoutTestActivity.java
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
}
output view (Correct)

I'm not sure if it makes any difference - but my suggestion is this:
Provide the android:id="@+id/linearLayout"-tag for the LinearLayout in your main.xml.
Then do this:
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);
    LinearLayout lt = (LinearLayout) findViewById( R.id.linearLayout );
    TextView tv = (TextView) getLayoutInflater().inflate(R.layout.text_view, null);
    lt.addView(tv);
}
You might also want to test if there is a difference between supplying null or your LinearLayout lt as the second parameter when inflating the TextView e.g.:
TextView tv = (TextView) getLayoutInflater().inflate(R.layout.text_view, lt);
                        If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With