Android: TextView 旁边的 ImageView 没有显示

Android: ImageView next to TextView not showing

我在 ListView 行中有一个 TextViewImageView,彼此相邻。但是,ImageView 根本没有显示,也没有记录点击。这是 XML 代码:

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

    <TextView
        android:id="@+id/textView"
        android:text="text"
        android:layout_width="320dp"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:layout_centerVertical="true"
        android:padding="10dp" />

    <ImageView
        android:id="@+id/imageView"
        android:clickable="true"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/textView"
        android:src="@drawable/ic_action"/>
</RelativeLayout>

问题似乎出在 layout_toRightOf 行,如果我将其删除,则会显示 ImageView,但在错误的位置。但我不明白为什么它会导致问题。我错过了什么?

问题是 TextViewImageView 推出了屏幕。

您可以使用 LinearLayoutandroid:layout_weight

来解决这个问题

例如:

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

    <TextView
        android:id="@+id/textView"
        android:text="text"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:layout_marginTop="10dp"
        android:layout_centerVertical="true"
        android:padding="10dp" />

    <ImageView
        android:id="@+id/imageView"
        android:clickable="true"
        android:layout_width="50dp"
        android:layout_height="50dp"
        android:layout_marginLeft="5dp"
        android:layout_marginRight="5dp"
        android:layout_centerVertical="true"
        android:layout_toRightOf="@id/textView"
        android:src="@drawable/ic_action"/>
</LinearLayout>

有关 layout_weight 属性的更多信息:

此属性根据视图应在屏幕上占据的大小 space 为视图分配 "importance" 值。较大的权重值允许它扩展以填充父视图中任何剩余的 space。子视图可以指定一个权重值,然后视图组中任何剩余的 space 将按照其声明的权重比例分配给子视图。默认权重为零。

例如,如果有三个文本域,其中两个声明权重为1,而另一个没有赋权,则第三个没有权重的文本域不会增长,只会占用其所需的区域内容。另外两个将同样扩展以填充所有三个字段测量后剩余的 space。如果第三个字段的权重为 2(而不是 0),那么它现在被声明为比其他两个都更重要,因此它获得剩余总数的一半 space,而前两个平分其余部分.

你需要使用带权重的LinearLayout..如果你设置固定宽度并且phone的尺寸很小,它要么会伸出屏幕。

//以水平方向做线性布局

<LinearLayout 
   ...
   orientation = "horizontal"
   ...
>

    <TextView
        ....
        android:layout_width="0dp"
        android:layout_weight="1"
        ...
    />

    <Button
       ....
       android:layout_width="wrap_content"
       ...
    />

</LinearLayout>

android:layout_weight,你就懂了