I am trying to translate this simple XML layout for Android into a programmatic equivalent in Java:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent" android:layout_height="wrap_content" android:id="@+id/ll">
<LinearLayout android:layout_width="wrap_content" android:layout_height="match_parent" android:id="@+id/ll22" android:gravity="left">
<TextView android:text="TextView" android:id="@+id/textView1" android:layout_width="wrap_content" android:layout_height="wrap_content"></TextView>
</LinearLayout>
<LinearLayout android:layout_height="match_parent" android:id="@+id/ll3" android:layout_width="match_parent" android:gravity="right">
<Button android:id="@+id/button1" android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
<Button android:id="@+id/button2" android:text="Button" android:layout_height="wrap_content" android:layout_width="wrap_content"></Button>
</LinearLayout>
</LinearLayout>
This is what I have so far in Java:
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout ll2 = new LinearLayout(this);
ll2.setGravity(Gravity.LEFT);
LinearLayout ll3 = new LinearLayout(this);
ll3.setGravity(Gravity.RIGHT);
TextView text = new TextView(this);
text.setText("Text");
ll2.addView(text);
Button button1 = new Button(this);
button1.setText("Button");
ll3.addView(button1);
Button button2 = new Button(this);
button2.setText("Button");
ll3.addView(button2);
ll.addView(ll2);
ll.addView(ll3);
setContentView(ll);
The problem with my Java is that the result is not lined up as nicely as the XML. Everything is scrunched together instead of being on opposite sides of the screen. I believe this is because I am unable to figure out how to set the Width of ll3 to “match_parent”.
Lastly, please do not suggest to me to just use the XML file within my Java such as ll = (LinearLayout) findViewById(R.layout.main.ll) . I’m aware of that option, but I’m trying to do this entirely programmatic in Java to get a better grasp on the Java side of the SDK.
Thanks.
Try this: