[英]Adding a view to a LinearLayout at a specified position
我有以下帶有LinearLayout的main.xml文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1" android:id="@+id/llid">
<TextView android:text="Client profile"
android:id="@+id/ProfileName"
android:layout_width="fill_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
</TextView>
<TextView android:text="Specs"
android:id="@+id/Specs"
android:layout_width="fill_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
</TextView>
</LinearLayout>
我在運行時通過代碼向LinearLayout添加一個圖像
ImageView image = new ImageView(this);
image.setImageBitmap(bmp);
LinearLayout ll = (LinearLayout) findViewById(R.id.llid);
ll.addView(image);
但是,我想在LinearLayout中的2個TextView之間添加ImageView。 我似乎無法在Android文檔中找到一種方法在另一個視圖之前或之后添加視圖。 我怎樣才能做到這一點?
注:我通話
setContentView(R.layout.main);
在我將ImageView添加到LinearLayout之前。
文檔聲明您可以使用索引將其插入所需的位置。 我看到你只使用了視圖的簽名,你是否嘗試了帶索引參數的簽名?
public void addView(View child, int index)
我遇到了類似的問題。 在我的情況下,我想在另一個LinearLayout的最后位置添加一個LinearLayout。 為了實現它,我做到了:
LinearLayout parentLayout = (LinearLayout) findViewById(R.id.parentLayout);
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
// add others views to your linear layout
parentLayout.addView(layout, parentLayout.getChildCount());
setContentView(R.layout.main);
ImageView img = (ImageView) findViewById(R.id.imagefield);
img.setImageResource(your_image_here);
並在xml中
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:weightSum="1"
android:id="@+id/llid">
<TextView android:text="Client profile"
android:id="@+id/ProfileName"
android:layout_width="fill_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
</TextView>
<ImageView android:id="@+id/imagefield"
android:layout_width="wrap_content"
android:layout_height="wrap_content">
</ImageView>
<TextView android:text="Specs"
android:id="@+id/Specs"
android:layout_width="fill_parent"
android:textStyle="bold"
android:layout_height="wrap_content"
android:gravity="center_horizontal">
</TextView>
</LinearLayout>
將ImageView添加到xml中,如果未使用它,則使其不可見(image.setVisibility(View.INVISIBLE))
。 當沒有設置圖像時,它可能無法顯示任何內容。
獲取視圖組中的視圖位置
val targetPosition = oldLL.indexOfChild(viewToAdd)
在視圖組中的位置添加視圖
newLL.addView(viewToAdd,targetPosition)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.