android - 如何按中心对齐按钮并进行偏移

标签 android layout android-view android-button

我想在中心对齐按钮并进行偏移我尝试过这样的方法 Is there a way to offset a view from center in Android?但它不起作用。例如:

<View
android:id="@+id/fakeView"
android:layout_width="10dp"
android:layout_height="10dp"
android:layout_centerInParent="true"
android:paddingTop="80dp"
android:background="#FFAABB" />

仍然保持中心

有什么方法可以这样实现:

enter image description here

更新:

我的完整布局:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent" >
     <ImageButton 
         android:layout_width="100dp"
         android:layout_height="100dp"
         android:layout_centerHorizontal="true"
         android:layout_marginLeft="100dp"
         />
</RelativeLayout>

最佳答案

一种方法是使用在相对布局内居中的 anchor View ,将按钮设置在它的右侧并设置边距。

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent" >

        <View
            android:id="@+id/anchor"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_centerInParent="true" />

         <ImageButton 
             android:layout_width="100dp"
             android:layout_height="100dp"
             android:layout_marginRight="50dp"
             android:layout_toRightOf="@+id/anchor"
             />


    </RelativeLayout>

或尝试:

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:gravity="center"  >

         <ImageButton 
             android:layout_width="100dp"
             android:layout_height="100dp"
             android:layout_marginRight="50dp"
             />

    </RelativeLayout>

关于android - 如何按中心对齐按钮并进行偏移,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13501891/

相关文章:

android - 以编程方式设置系统设置 "use only 2g networks"

java - 无法读取Firebase数据库,数据返回null

java - 如何更改弹出布局的背景?

android - 在 robotium 上测试 wifi 时出现安全异常

android - android手机usb绑定(bind)后如何获取系统ip地址?

html - 网格布局容器中没有高度

java - 如何使组件在面板的特定区域内居中

android - ViewPager 内的 TabLayout 禁止滑动

java - Android Studio中 "View v"的含义

android - 使用 API 8 旋转广告 View