【问题标题】:Android RelativeLayoutAndroid 相对布局
【发布时间】:2011-04-07 00:01:31
【问题描述】:

我对 Android 开发非常陌生,我正在尝试弄清楚如何使用 RelativeLayout 标签来定位我的视图。我的目标是在左侧有一个大的 TextView,在它的右侧有两个 ButtonView,彼此堆叠。这是我正在使用的 XML 代码:

 <?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
       android:id="@+id/main_layout"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent"
       android:background="@drawable/wood_tile">
       <TextView
          android:id="@+id/life_counter"
          android:layout_width="fill_parent"
          android:layout_height="wrap_content"
          android:text="00" />
       <Button android:text="@string/button_up"
          android:id="@+id/button_up"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_toRightOf="@id/life_counter"/>
       <Button android:text="@string/button_down"
          android:id="@+id/button_down"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" 
          android:layout_below="@id/button_up"/>
    </RelativeLayout>

我觉得我一定没有正确使用标签。有人可以解释它是如何工作的吗?提前致谢。

【问题讨论】:

    标签: android xml


    【解决方案1】:

    您将左侧 TextView 的宽度设置为fill_parent,这将使其占据整个屏幕。任何放在它右边的东西都将不在屏幕上。为相关布局中的元素使用wrap_content 或特定宽度。

    你的方法也有点不对劲。如果您希望两个按钮对齐到屏幕右侧,请使用:

    <RelativeLayout 
       android:id="@+id/main_layout"
       android:layout_width="fill_parent"
       android:layout_height="fill_parent">
    
       <TextView
          android:id="@+id/life_counter"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:text="00" />
    
       <Button android:text="Button Up"
          android:id="@+id/button_up"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content"
          android:layout_alignParentRight="true"/>
    
       <Button android:text="Button Down"
          android:id="@+id/button_down"
          android:layout_width="wrap_content"
          android:layout_height="wrap_content" 
          android:layout_alignParentRight="true"
          android:layout_below="@+id/button_up"/>
    </RelativeLayout>
    

    【讨论】:

    • 谢谢,现在所有视图都可见了!至于你的第二部分,我真正想做的是将所有三个居中,而不是分别左右对齐。我也必须弄清楚如何做到这一点。
    • 要使它们居中,您需要将它们放置在具有android:layout_centerInParent="true 属性的嵌套RelativeLayout 中。见this solution
    • 美丽。这很好。感谢您的大力帮助!
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2022-01-17
    • 2015-11-24
    • 1970-01-01
    • 1970-01-01
    • 2016-11-05
    • 2013-11-23
    • 2014-02-14
    相关资源
    最近更新 更多