将视图添加到指定位置的LinearLayout

我有一个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文档中find一种方法在另一个视图之前或之后添加视图。 我怎样才能做到这一点?

NB我打电话

 setContentView(R.layout.main); 

将ImageView添加到LinearLayout之前。

View添加到ViewGroup ,可以指定一个索引来设置视图在父级中的位置。

你有两个意见,所以(从零开始计算)你想在第一个位置添加; 只需调用ll.addView(image, 1); 把它放在两个TextViews之间。

文档声明您可以使用索引将其插入到您想要的位置。 我看到你只使用视图的签名,你是否尝试用索引参数签名?

 public void addView(View child, int index) 
 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的最后位置添加一个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()); 

将一个ImageView添加到xml中,如果没有使用它,使其不可见(image.setVisibility(View.INVISIBLE)) 。 当没有图像设置时,它可能不显示任何东西。