让android控件水平居中

本文提供了一种简单的方法,在Android布局中通过设置`android:layout_gravity`属性为`center`来使按钮位于屏幕中央。还介绍了另一种使用`RelativeLayout`并设置`android:layout_centerInParent=true`的解决方案,适用于更复杂的需求。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

         

如何将一个button放在屏幕中间?

  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:orientation="vertical"
  4. android:layout_width="fill_parent"
  5. android:layout_height="fill_parent">

  6. <ImageButton android:id="@+id/btnFindMe"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_gravity="center_vertical|center_horizontal"
  10. android:background="@drawable/findme"></ImageButton>

  11. </LinearLayout>
评论 (0) •   •  链接 •  2012-02-24 
3个答案
       
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  3. android:layout_width="fill_parent"  
  4. android:layout_height="fill_parent"  
  5. android:gravity="center|center_horizontal|center_vertical" >  
  6. // 上面gravity属性的参数:center为居中,center_horizontal为水平居中,center_vertical为垂直居中  
  7. <Button  
  8. android:id="@+id/Binding_button"  
  9. android:layout_width="wrap_content"  
  10. android:layout_height="wrap_content"  
  11. android:text="关联新账户" ></Button>
  12. </LinearLayout>

这么写就可以了。

小飞
小飞
6749
编辑于  2012-03-02
评论 (1) •  链接 • 2012-02-24
  • 0
    试一试,可以用。 –  李剑波  2012-02-24

    这种方法是可行的,但是缺陷是layout中只能有一个控件,假如我左边、中间、右边各放一个,就不行了



@马擎方法可以用。找到另外一种方法,使用RelativeLayout,并且设置android:layout_centerInParent="true"

       
  1. <?xml version="1.0" encoding="utf-8"?>
  2. <RelativeLayout android:id="@+id/RelativeLayout01"
  3. android:layout_width="fill_parent"
  4. android:layout_height="fill_parent"
  5. xmlns:android="http://schemas.android.com/apk/res/android">

  6. <ImageButton android:id="@+id/btnFindMe"
  7. android:layout_width="wrap_content"
  8. android:layout_height="wrap_content"
  9. android:layout_centerInParent="true"
  10. android:background="@drawable/findme"></ImageButton>

  11. </RelativeLayout>
评论 (0) •  链接 • 2012-02-24
这种方法可行,扩展性好

你的代码的第十行改为

       
  1. android:layout_gravity="center"

这样就可以了


这种方法不行的

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值