帮助我将一个简单的Android XML布局翻译成Java
我正在尝试将Android的这个简单XML布局转换为Java中的编程等价物:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:安卓="http://schemas.安卓.com/apk/res/安卓"安卓:layout_width="match_parent" 安卓:layout_height="wrap_content" 安卓:id="@+id/ll">
<LinearLayout 安卓:layout_width="wrap_content" 安卓:layout_height="match_parent" 安卓:id="@+id/ll22" 安卓:gravity="left">
<TextView 安卓:text="TextView" 安卓:id="@+id/textView1" 安卓:layout_width="wrap_content" 安卓:layout_height="wrap_content"></TextView>
</LinearLayout>
<LinearLayout 安卓:layout_height="match_parent" 安卓:id="@+id/ll3" 安卓:layout_width="match_parent" 安卓:gravity="right">
<Button 安卓:id="@+id/button1" 安卓:text="Button" 安卓:layout_height="wrap_content" 安卓:layout_width="wrap_content"></Button>
<Button 安卓:id="@+id/button2" 安卓:text="Button" 安卓:layout_height="wrap_content" 安卓:layout_width="wrap_content"></Button>
</LinearLayout>
</LinearLayout>
到目前为止,我在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);
我的Java的问题是,结果没有XML那么好地排列。所有东西都挤在一起,而不是在屏幕的两侧。我相信这是因为我不知道如何将ll3的宽度设置为“匹配父项”
最后,请不要建议我只在Java中使用XML文件,例如ll=(LinearLayout)findViewById(R.layout.main.ll)。我知道这个选项,但我正在尝试完全用Java编程,以便更好地掌握SDK的Java方面
谢谢
# 1 楼答案
试试这个: