[英]Android way to add new xml layout
我有一個帶有布局的活動。 在對服務器執行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添加的任何樣式。
添加具有如此多樣式的元素的最佳方法是什么? 為什么這不起作用?
這些textview被添加但彼此之上
那就是您告訴RelativeLayout
要做的。 如果要指定定位規則,則在添加TextView
小部件時addView()
RelativeLayout.LayoutParams
實例傳遞給addView()
。
添加具有如此多樣式的元素的最佳方法是什么?
好吧,答案可能是使用ListView
或RecyclerView
。 話雖如此,保持垂直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()
調用。 這也假定該代碼段位於承載此UI的活動的方法中。
如果要使用重復的布局,為什么不選擇使用自定義襯紙布局。
此鏈接上提到了一個簡單的基本解決方案http://android-coding-tuts.blogspot.in/2012/02/custom-listview-with-sliding-view-for.html
您應該為此查找碎片。 它們具有單獨的控制視圖結構,您可以為每個子視圖創建一個新片段。
在這里查看:
http://developer.android.com/guide/components/fragments.html
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.