Android布局重叠按钮在彼此顶部(相同的中心)

时间:2014-08-07 00:04:21

标签: android android-layout

因此,初始布局包含一个大的圆形“父”按钮和多个圆形“子”按钮,这些按钮位于父按钮后面。因此,所有子按钮与父按钮共享相同的中心。这种布局的原因是在运行时,我可以使用translateXtranslateY将子按钮移入和移出父按钮。

diagram

但是,我坚持初始布局。如何在不对任何子属性进行硬编码的情况下将子按钮居中到父按钮的中心?

3 个答案:

答案 0 :(得分:0)

使视图大小相同,并为子项添加填充,以便减少它们。如果视图全部位于相同位置,则布局将如您所愿。无论如何,您始终可以在代码中更改属性。

答案 1 :(得分:0)

将所有视图放在android:gravity="center"内(可能将FrameLayout嵌套在另一个布局中)后,对所有视图使用FrameLayout。然后,您可以通过更改layout_margin *值来偏移每个Button在其父级中的位置。或者你可以翻译包含你想要的所有按钮的父FrameLayout。

要使按钮变为圆形,请更改button's android:background value to point to a custom selector

答案 2 :(得分:0)

我使用容器RelativeLayout作为锚来解决这个问题,父按钮和所有子按钮都是android:layout_centerInParent。然后,为了解决离开容器时子按钮消失的问题,我给了容器android:clipChildren(false)set clipChildren to false on all of its ancestors as well

请注意,容器必须大于其所有子元素,否则所有子元素将被剪裁为相同的尺寸,即使它们移动到容器外部!为了解决这个问题,我给容器的宽度和高度为wrap_content

因此,无论我在哪里放置父母按钮,我的所有子按钮都都在父按钮的中心位置,并且子按钮也可以自由移动。

修改

这方面的一个主要缺陷是,如果按钮不在父母之外,则无法接收触摸事件。要解决这个问题,您可以use event coordinates或使父容器足够大,以便始终包含子元素(可能是屏幕宽度/高度的两倍?)

screenshot

以下是代码:

<强> RES /布局/ listfragment.xml

<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:clipChildren="false" >

    <ListView
        android:id="@android:id/list"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

    <RelativeLayout
        android:onClick="onButterflyMenuClicked"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|right"
        android:layout_marginBottom="20sp"
        android:layout_marginRight="15sp"
        android:clipChildren="false" >

        <Button
            android:id="@+id/btn_north_1"
            style="@style/PeekabooButton"
            android:text="1st"
            android:translationY="-65sp" />

        <Button
            android:id="@+id/btn_north_2"
            style="@style/PeekabooButton"
            android:text="2nd"
            android:translationY="-115sp" />

        <Button
            android:id="@+id/kingbutton"
            android:layout_width="65sp"
            android:layout_height="65sp"
            android:layout_centerInParent="true"
            android:gravity="center_vertical|center_horizontal"
            android:textSize="16sp"
            android:text="KING" />

    </RelativeLayout>

</FrameLayout>

<强> RES /值/ styles.xml

<style name="PeekabooButton">
    <item name="android:layout_width">45sp</item>
    <item name="android:layout_height">45sp</item>
    <item name="android:layout_centerInParent">true</item>
    <item name="android:textSize">10sp</item>
</style>