【问题标题】:are android toast messages forced to wrap_content layout_width?android toast 消息是否强制 wrap_content layout_width?
【发布时间】:2017-01-31 22:31:06
【问题描述】:

我正在创建一个自定义视图以与 android.widget.Toast.setView() 一起使用,但无论我如何调整视图大小,所有内容似乎都使用“wrap_content”作为布局宽度设置进行布局。

例如,无论我将视图的根布局(在我的情况下为线性布局)宽度设置为“match_parent”还是指定静态大小(例如“500dp”),我在运行时都会得到相同的结果...... toast 只是包装了内容.

我的布局 XML 是:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/toast_container"
    android:orientation="horizontal"
    android:layout_width="500dp"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:background="@drawable/toast_bg">
    <ImageView
        android:id="@+id/toastIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:src="@drawable/toast_icon" />
    <TextView
        android:id="@+id/toastMsg"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sample toast message"/>
</LinearLayout>

我怀疑 Android(我在 API 19 Kit-Kat 平台上运行)将 toast 视图强制为“wrap_content”。是这样吗?

我确定有人会建议我查看 AOSP 中的源代码。如果我手头有代码,我会这样做。

【问题讨论】:

    标签: android toast android-toast


    【解决方案1】:

    我在我的应用程序中这样做,它适用于定义的宽度。

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    
    android:id="@+id/toast_container"
    android:orientation="horizontal"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="16dp"
    >
    
    <RelativeLayout
        android:layout_width="800dp"
        android:layout_height="wrap_content"
        android:background="@drawable/toast_bg">
    <ImageView
        android:id="@+id/toastIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="16dp"
        android:src="@drawable/toast_icon" />
    <TextView
        android:id="@+id/toastMsg"
        android:layout_toRightOf="@+id/toastIcon"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="sample toast message"/>
    </RelativeLayout>
    

    我设置了 RelativeLayout 的宽度,它对我有用。试试这个。

    【讨论】:

    • 确实,添加额外的嵌套RelativeLayout 解决了这个问题。它以这种方式工作似乎很奇怪而且过分,但确实如此。
    • 我想知道是否任何嵌套布局都可以工作,或者这是否需要嵌套的 RelativeLayout?
    猜你喜欢
    • 2011-07-15
    • 2011-12-09
    • 2014-07-04
    • 1970-01-01
    • 2021-11-06
    • 2014-01-07
    • 1970-01-01
    • 2015-04-08
    • 1970-01-01
    相关资源
    最近更新 更多