0

I'm creating a custom view to use with android.widget.Toast.setView(), but no matter how I size the view, everything seems to be laid out using "wrap_content" as the layout width setting.

For example, whether I set the view's root layout (LinearLayout in my case) width to 'match_parent' or specify a static size such as "500dp" I get the same result at runtime ... the toast simply wraps the content.

My layout XML is:

<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>

I suspect that Android (I'm running in an API 19 Kit-Kat platform) is forcing toast views to be 'wrap_content.' Is that so?

I'm sure someone is going to suggest I look at the source code in the AOSP. If I had the code handy, I would do that.

alpartis
  • 1,086
  • 14
  • 29

1 Answers1

0

I am doing like this in my app and it works for defined width.

<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>

I set the width of the RelativeLayout and it works for me. Try this.

Zaartha
  • 1,106
  • 9
  • 25
  • Indeed, adding the extra nested RelativeLayout resolves the issue. Seems odd and excessive that it works this way, but it does. – alpartis Feb 01 '17 at 05:27
  • I wonder if any nested layout would work, or does this require a nested RelativeLayout? – alpartis Feb 01 '17 at 06:00