安卓和布局

标签 android android-layout

我需要在 View 中定位文本:

文本 'Some more text' 应该位于 bottom|center_horizo​​ntal

文本“短文本”应位于右对齐位置,但距离屏幕顶部约 10%

文本 'x.x.x.x' 应该与屏幕中心对齐(右对齐/下对齐第一个四分之一)

text 'Some long text ..' 应该与屏幕第三个四分之一的顶部/左侧对齐,但它应该穿过屏幕的 center_horizo​​ntal。

最佳答案

这里有几个快速指南:

  1. Android 布局的嵌套往往比您通常预期的要深得多。您通常会以“空”布局结束,这些布局只占用空间,以便其他元素正确布局。
  2. 当您将文本对齐到特定边缘时,RelativeLayout 是您的好 helper 。
  3. 使用填充设置将文本“稍微远离”边缘。
  4. Gravity 对齐 TextView 或按钮中的文本。

再看一遍你的图表,我是这样复制的:

  1. 从占据整个屏幕的相对布局(“fill_content”)开始。
  2. 通过锚定到顶部和底部来放入“短文本”和“更多文本”。
  3. 在中间放置一个具有“centerInParent”属性的零宽度项目 屏幕。
  4. 将剩余的项目放在上面并与该中心点对齐。

不幸的是,第 4 步中的任何一项都无法正常工作。当引用的项目是 centerInParent 项目时,“layout_below”之类的东西不起作用。与第 3 步的相对布局。原来它与未能在顶层填充内容有关。是的,布局很棘手,我希望有一个调试器。

这是正确的版本:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/r1"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<TextView
    android:id="@+id/short_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Short Text"
    android:gravity="right"
    android:layout_marginTop="30dip"
    android:layout_alignParentTop="true" />
<TextView
    android:id="@+id/more_text"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    android:text="Some More Text"
    android:gravity="center"
    android:layout_alignParentBottom="true" />
  <TextView android:id="@+id/centerpoint"
    android:layout_centerInParent="true"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:width="0dip"
    android:height="0dip"
    />
  <TextView android:id="@+id/run_fox"
    android:text="Run, fox, run!"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_above="@id/centerpoint"
    android:layout_toLeftOf="@id/centerpoint" 
    />
<TextView
    android:layout_below="@id/centerpoint"
    android:text="The quick brown fox jumped over the lazy dog, who had been a frog, and then got features and ran slowly."
    android:layout_alignRight="@id/centerpoint"
    android:layout_width="fill_parent"
    android:layout_height="wrap_content"
    />
 </RelativeLayout>

关于安卓和布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2990882/

相关文章:

android - 如何在Android布局中布局不规则形状

javascript - Phonegap - 如何摆脱未捕获的类型错误

android - 无论屏幕大小如何,都将两个按钮设置为相同宽度?

java - 将 Java 项目转换为 Android 项目

Android - xml布局作为背景

android - 如何使 gridView 的所有项目具有相同的大小?

java - 适用于 Mac OSX Catalina 的 Android studio 3.5 在索引进程中崩溃

android - 如何开发返回 JSON 数据的 Web 服务

android - android :layout_gravity and android:gravity之间的区别

java - 仅通过 XML(无需其他可绘制对象)单击时如何更改按钮的颜色?