I create a very simple activity where I create and set the view in java code instead of xml. The width I pass to the outer LinearLayout though has no effect at all (200). The view is displayed on the entire width of the screen, no matter what value I pass here.
(Note that this is just sample code; I know that in a real app you don't use fixed values. I just want to point out my problem here for easier clarification).
public class MyActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// outer linear layout
LinearLayout ll = new LinearLayout(this);
ll.setLayoutParams(new LinearLayout.LayoutParams(
200, // *** this param has no effect, regardless of the value I set here ***
LinearLayout.LayoutParams.FILL_PARENT
));
ll.setBackgroundColor(Color.parseColor("#00ff00"));
// inner linear layout
LinearLayout ll2 = new LinearLayout(this);
ll2.setLayoutParams(new LinearLayout.LayoutParams(
100, // ** this width for the inner view is working fine **
LinearLayout.LayoutParams.FILL_PARENT
));
ll2.setBackgroundColor(Color.parseColor("#0000ff"));
ll.addView(ll2);
setContentView(ll);
}
}
But if I replace setContentView(ll);
and use a xml layout instead where the outer LinearLayout has a value of 200px, it's applied properly and the view only takes 200px of the screen.
setContentView(com.example.R.layout.main);
where main.xml is:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="200px"
android:layout_height="fill_parent"
android:background="#ff0000"
>
<TextView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="@string/hello"
/>
</LinearLayout>
Why does setting a fixed width in java code for the outer layout has no effect?