在android中放置/重叠(z-index)视图上方的另一个视图

我有一个线性布局,其中包括imageview和textview,一个线性布局下一个。

<LinearLayout android:orientation="horizontal" ... > <ImageView android:id="@+id/thumbnail" android:layout_weight="0.8" android:layout_width="0dip" android:layout_height="fill_parent"> </ImageView> <TextView android:id="@+id/description" android:layout_weight="0.2" android:layout_width="0dip" android:layout_height="wrap_content"> </TextView> 

有些规则可能会丢失,这是一个想法,布局如何看起来。 我想另一个长度和宽度的50dip的小文本视图,放在imageview上,“over”我的意思是z-index比imageview更多,我想把它放在imageview的中心和上面(重叠)。

我想知道怎样才能把一个视图放在另一个视图的上方,并使用不同的z-index(最好是线性布局)?

你不能使用这个LinearLayout,但你可以使用FrameLayout 。 在FrameLayout ,z索引由项目的添加顺序来定义,例如:

 <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="fill_parent" android:layout_height="wrap_content" > <ImageView android:layout_width="wrap_content" android:layout_height="wrap_content" android:src="@drawable/my_drawable" android:scaleType="fitCenter" /> <TextView android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="bottom|center" android:padding="5dp" android:text="My Label" /> </FrameLayout> 

在这种情况下,TextView将会在ImageView的顶部,沿着图像的底部中心绘制。

RelativeLayout以相同的方式工作,相对布局中的最后一个图像获胜。

改变绘制顺序

另一种方法是更改​​父级绘制视图的顺序。 你可以通过调用setChildrenDrawingOrderEnabled(true)和覆盖getChildDrawingOrder(int childCount,int i)来从ViewGroup启用这个特性。

例:

 /** * Example Layout that changes draw order of a FrameLayout */ public class OrderLayout extends FrameLayout { private static final int[][] DRAW_ORDERS = new int[][]{ {0, 1, 2}, {2, 1, 0}, {1, 2, 0} }; private int currentOrder; public OrderLayout(Context context) { super(context); setChildrenDrawingOrderEnabled(true); } public void setDrawOrder(int order) { currentOrder = order; invalidate(); } @Override protected int getChildDrawingOrder(int childCount, int i) { return DRAW_ORDERS[currentOrder][i]; } } 

输出:

使用0-1-2调用OrderLayout#setDrawOrder(int)将得到:

在这里输入图像描述 在这里输入图像描述 在这里输入图像描述

你可以使用view.setZ(float)从API级别21开始。 在这里你可以find更多的信息。

有一种使用LinearLayout的方法。 只需将上一个元素的marginTop设置为相应的负值,并确保最上面的元素在XML中的元素之后。

 <linearLayout android:orientation="horizontal" ... > <ImageView android:id="@+id/thumbnail" android:layout_weight="0.8" android:layout_width="0dip" android:layout_height="fill_parent" > </ImageView> <TextView android:id="@+id/description" android:layout_marginTop="-20dip" android:layout_weight="0.2" android:layout_width="0dip" android:layout_height="wrap_content" > </TextView> 

AFAIK你不能做线性布局,你必须去一个RelativeLayout 。

在RelativeLayout中试试这个:

 ImageView image = new ImageView(this); image.SetZ(float z); 

它适用于我。