gpt4 book ai didi

java - 帮我把一个简单的 Android XML 布局翻译成 Java

转载 作者:行者123 更新时间:2023-11-30 09:47:17 27 4
gpt4 key购买 nike

我正在尝试将这个简单的 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 端。

谢谢。

最佳答案

试试这个:

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

关于java - 帮我把一个简单的 Android XML 布局翻译成 Java,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/6740309/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com