【问题标题】:layout_toRightOf works and layout_toLeftOf doesn't, how to solve?layout_toRightOf 有效而 layout_toLeftOf 无效,如何解决?
【发布时间】:2016-11-23 22:49:47
【问题描述】:

我有简单的相对布局 - 一个 ImageView (iv1) 和一个 TextView (tv1) 在 iv1 的左侧。不幸的是,我没有看到tv1。更何况连hierarchyViewer都帮我找不到了。

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:gravity="right"
android:background="@android:color/white"
>

<ImageView
    android:id="@+id/iv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:src="@drawable/ic_launcher" />

<TextView
    android:id="@+id/tv1"
    android:layout_toLeftOf="@+id/iv1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="TextView" />

</RelativeLayout>

看起来是这样的:

但是,如果我将 android:layout_toLeftOf="@+id/iv1" 更改为 android:layout_toRightOf="@+id/iv1",我的文本视图将位于图像视图的右侧。似乎 toRightOf 有效,而 toLeftOf 无效。 如下所示:

这是怎么回事?如何让 layout_toLeftOf 工作?

【问题讨论】:

    标签: android android-layout


    【解决方案1】:

    变化:

    <TextView
        android:id="@+id/tv1"
        android:layout_toLeftOf="@+id/+iv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
    

    到:

    <TextView
        android:id="@+id/tv1"
        android:layout_toLeftOf="@id/iv1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView" />
    

    您在 TextView 的 toLeftOf 中使用 @+id/iv1 而不是 @id/iv1。 此外,您应该在视图中为图像视图指定一个特定位置。尝试对齐它:layout_parentTop = true

    【讨论】:

    • 据我了解,@+id 意味着创建一个新的 id,@id 意味着使用已经存在的对象。但是,如果我按照您的建议替换布局,则会收到“无法解析资源 @id/iv1”。是什么原因造成的?
    • 如果您在尝试查看布局(不是代码,而是实际视图)时得到它,这是一个错误。有时 Eclipse 不会在您的布局中进行更改。我有时会通过在 xml 代码和布局视图之间切换两次来解决这个问题...
    【解决方案2】:

    设置imageview属性align_parent_right= true;

    【讨论】:

      【解决方案3】:

      在我的情况下(不在此布局中),RelativeLayout 的android:layout_width 存在问题。当它是wrap_contentmatch_parent 时,布局变得分散。例如,当我将其设置为 300dp 时,一切都很好。

      【讨论】:

        猜你喜欢
        • 2020-04-21
        • 2015-09-12
        • 2022-01-11
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2021-08-22
        • 2018-02-26
        • 1970-01-01
        相关资源
        最近更新 更多