gpt4 book ai didi

java - Android 方式添加新的 xml 布局

转载 作者:行者123 更新时间:2023-11-29 20:47:38 25 4
gpt4 key购买 nike

我有一个带有布局的 Activity 。在向服务器发出 GET 请求后,我想向该布局动态添加新元素。

我想使用 for 结构多次添加这些元素。

我要添加的元素如下:

<RelativeLayout  xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="64dp"
android:background="@drawable/outer_border"
android:padding="2dp"
android:layout_marginTop="20dp">

<TextView
android:id="@+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true"
android:background="@color/orange"
android:height="40dp"
android:paddingLeft="5dp"
android:paddingTop="5dp"
android:text="TW"
android:textAppearance="?android:attr/textAppearanceLarge"
android:textColor="#ffffff"
android:textSize="70px"
android:width="60dp" />

<CheckBox
android:id="@+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true" />

<TextView
android:id="@+id/textView2"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignBottom="@+id/textView3"
android:layout_toLeftOf="@+id/checkBox1"
android:text="inca 6 zile"
android:textAppearance="?android:attr/textAppearanceSmall" />

</RelativeLayout>

我已经试过了:

for(int i = 0; i < homeworkList.size(); i++){
LinearLayout linearLayout = (LinearLayout) currentActivity.findViewById(R.id.linearLayout2);

RelativeLayout newLayout = new RelativeLayout(currentActivity, null, R.style.HomeworkLayout);

TextView text = new TextView(currentActivity);
TextView text1 = new TextView(currentActivity);
text1.setText("da");
text.setText("nu");

newLayout.addView(text1);
newLayout.addView(text);

linearLayout.addView(newLayout, relativeParams);
}

但没有结果,那些 textview 被添加但在彼此之上,我刚刚添加的相对布局没有任何我使用 R.style.HomeworkLayout 添加的样式。

添加具有如此多样式的元素的最佳方法是什么?为什么这不起作用?

最佳答案

those textview were added but on top of each other

这就是您告诉 RelativeLayout 要做的事情。如果您想指定定位规则,您可以在添加 TextView 小部件时将 RelativeLayout.LayoutParams 的实例传递给 addView()

What is the best way to add the elements with so much styling?

嗯,答案可能是使用 ListViewRecyclerView。话虽如此,保持垂直 LinearLayout 的最简单解决方案是增加行数:

LinearLayout linearLayout = (LinearLayout) currentActivity.findViewById(R.id.linearLayout2);

for(int i = 0; i < homeworkList.size(); i++){
View row=getLayoutInflater().inflate(R.layout.row, linearLayout, false);

// call findViewById() to retrieve your TextView widgets and fill them in

linearLayout.addView(row);
}

这假设您在问题中显示的布局名为 R.layout.row;如果这不是名称,请根据需要调整 inflate() 调用。这还假定代码 fragment 位于托管此 UI 的 Activity 的方法中。

关于java - Android 方式添加新的 xml 布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/30014796/

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