[英]Adding content to a linear layout dynamically?
例如,如果我定義了一個方向為垂直的根線性布局:
main.xml :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_root"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
<!-- I would like to add content here dynamically.-->
</LinearLayout>
在根線性布局內部,我想添加多個子線性布局,每個子線性布局方向都是水平的。 有了所有這些,我最終可以得到一個像 output 這樣的表。
例如具有子布局的根,例如:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/my_root"
android:layout_height="wrap_content"
android:layout_width="fill_parent"
android:orientation="vertical"
<!-- 1st child (1st row)-->
<LinearLayout
...
android:orientation="horizontal">
<TextView .../>
<TextView .../>
<TextView .../>
</LinearLayout>
<!-- 2nd child (2nd row)-->
...
</LinearLayout>
由於子線性布局的數量及其內容非常動態,我決定以編程方式將內容添加到根線性布局。
如何以編程方式將第二個布局添加到第一個布局,這還可以為每個子級設置所有布局屬性並在子級內部添加更多其他元素?
在您的onCreate()
中,編寫以下內容
LinearLayout myRoot = (LinearLayout) findViewById(R.id.my_root);
LinearLayout a = new LinearLayout(this);
a.setOrientation(LinearLayout.HORIZONTAL);
a.addView(view1);
a.addView(view2);
a.addView(view3);
myRoot.addView(a);
view1
, view2
和view3
是你的TextView
s。 它們很容易以編程方式創建。
LinearLayout layout = (LinearLayout)findViewById(R.id.layout);
View child = getLayoutInflater().inflate(R.layout.child, null);
layout.addView(child);
您可以像這樣實現 LinearLayout 級聯:
LinearLayout root = (LinearLayout) findViewById(R.id.my_root);
LinearLayout llay1 = new LinearLayout(this);
root.addView(llay1);
LinearLayout llay2 = new LinearLayout(this);
llay1.addView(llay2);
我找到了更准確的方法來在 kotlin 中添加像線性布局這樣的視圖(在 inflate() 和 false 中傳遞父布局)
val parentLayout = view.findViewById<LinearLayout>(R.id.llRecipientParent)
val childView = layoutInflater.inflate(R.layout.layout_recipient, parentLayout, false)
parentLayout.addView(childView)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.