【问题标题】:Help me translate a simple Android XML Layout into Java帮我把一个简单的 Android XML Layout 翻译成 Java
【发布时间】:2011-10-08 02:13:04
【问题描述】:

我正在尝试将这个用于 Android 的简单 XML 布局转换为 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>

这是我目前在 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 的宽度设置为“match_parent”。

最后,请不要建议我只在我的 Java 中使用 XML 文件,例如 ll = (LinearLayout) findViewById(R.layout.main.ll) 。我知道该选项,但我正尝试在 Java 中完全以编程方式执行此操作,以便更好地掌握 SDK 的 Java 端。

谢谢。

【问题讨论】:

    标签: java android xml android-layout


    【解决方案1】:

    试试这个:

    ll3.setLayoutParams(new LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.FILL_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT
        ));
    

    【讨论】:

    • 完美。非常感谢:)
    猜你喜欢
    • 1970-01-01
    • 2011-11-09
    • 1970-01-01
    • 2021-02-03
    • 2013-12-23
    • 1970-01-01
    • 2011-05-09
    • 2011-03-07
    • 2018-03-26
    相关资源
    最近更新 更多