如何在FrameLayout中将元素右对齐?

Hou*_*ine 19 android android-xml android-framelayout

我有一个包含2个视图的FrameLayout,第二个是类似a的东西Close Button (X),我想把它放在右边.

我已经尝试过layout_gravity ="正确",但这不起作用.

这是我的布局xml:

<FrameLayout android:layout_width="320dp"
    android:layout_height="wrap_content"
    android:id="@+id/layoutSmallImg">

    <ImageView android:id="@+id/bigImage"
        android:layout_width="320dp" android:layout_height="wrap_content"/>

    <ImageView android:id="@+id/bigImage"
        android:layout_width="320dp" android:layout_height="wrap_content"/>

    <ImageButton android:id="@+id/closebutton"
        android:background="@android:color/transparent"
        android:layout_height="30dp" android:layout_marginTop="10dp"
        android:layout_alignParentRight="true"
        android:layout_width="30dp" android:paddingLeft="40dp"
        android:visibility="gone" 
        android:src="@drawable/close" />
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)

Ale*_*dam 31

我建议你RelativeLayout改用

FrameLayout旨在阻止屏幕上的某个区域显示单个项目.您可以将多个子项添加到FrameLayout,并使用重力控制它们在FrameLayout中的位置.孩子们被堆成一堆,最近添加的孩子在上面.框架布局的大小是其最大子项(加上填充)的大小,可见或不可见(如果FrameLayout的父级允许).仅当setConsiderGoneChildrenWhenMeasuring()设置为true时,GONE视图才会用于调整大小.

顺便说一下,你想要ImageView顶部或旁边的按钮吗?您将布局和imageView的宽度设置为相同的大小.


评论后,我可以看到两个选项:


小智 22

阅读DOCS:

FrameLayout旨在阻止屏幕上的某个区域显示单个项目.通常,FrameLayout应该用于保存单个子视图,因为很难以可扩展到不同屏幕大小而儿童不会相互重叠的方式组织子视图.但是,您可以使用android:layout_gravity属性将多个子项添加到FrameLayout并通过为每个子项分配重力来控制它们在FrameLayout中的位置.

尝试:

<TextView
     .....
     android:layout_gravity="right" />
Run Code Online (Sandbox Code Playgroud)

您可以在FrameLayout中的9个不同位置放置视图

请享用


Gen*_*kin 9

只需将FrameLayout中的元素放入第二个RelativeLayout即可.并使用android:layout_alignParentRight ="true"表示要对齐的元素.

<FrameLayout android:layout_width="320dp" android:layout_height="wrap_content" 
                                      android:id="@+id/layoutSmallImg">
 <RelativeLayout
            android:id="@+id/content"
            android:layout_width="match_parent"
            android:layout_height="match_parent" >
    <ImageView android:id="@+id/bigImage"
            android:layout_width="320dp" 
            android:layout_height="wrap_content"/>

    <ImageButton android:id="@+id/closebutton"
            android:background="@android:color/transparent"
            android:layout_height="30dp" android:layout_marginTop="10dp"
            android:layout_alignParentRight="true"
            android:layout_width="30dp" android:paddingLeft="40dp"
            android:visibility="gone" 
            android:src="@drawable/close" />
  </RelativeLayout>
</FrameLayout>
Run Code Online (Sandbox Code Playgroud)