Добавление изображения в тост? - PullRequest
59 голосов
/ 27 сентября 2011

Можно ли программно добавить изображение во всплывающее окно с тостами?

Ответы [ 7 ]

84 голосов
/ 28 сентября 2011

Да , вы можете добавить просмотр изображения или любой вид в уведомление о тосте, используя метод setView (), используя этот метод, вы можете настроить Toast согласно вашему требованию.

Здесь яЯ создал файл пользовательского макета для накачки в уведомление Toast, а затем я использовал этот макет в уведомлении Toast с помощью метода setView ().

cust_toast_layout.xml

<?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="match_parent"
  android:id="@+id/relativeLayout1"
  android:background="@android:color/white">

    <TextView
        android:textAppearance="?android:attr/textAppearanceLarge"
        android:id="@+id/textView1" android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="PM is here"
        android:gravity="center"
        android:textColor="@android:color/black">
    </TextView>

    <ImageView
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:src="@drawable/new_logo"
        android:layout_below="@+id/textView1"
        android:layout_margin="5dip"
        android:id="@+id/imageView1">
    </ImageView>

    <TextView
        android:id="@+id/textView2"
        android:layout_height="wrap_content"
        android:layout_width="fill_parent"
        android:text="This is the demo of Custom Toast Notification"
        android:gravity="center"
        android:layout_below="@+id/imageView1"
        android:textColor="@android:color/black">
    </TextView>

</RelativeLayout>

CustomToastDemoActivity.java

LayoutInflater inflater = getLayoutInflater();
View view = inflater.inflate(R.layout.cust_toast_layout, 
    (ViewGroup)findViewById(R.id.relativeLayout1));

Toast toast = new Toast(this);
toast.setView(view);
toast.show();
21 голосов
/ 20 апреля 2013

Просто используйте следующее:

Toast toast = new Toast(myContext);
ImageView view = new ImageView(myContext); 
view.setImageResource(R.drawable.image_icon); 
toast.setView(view); 
toast.show();
14 голосов
/ 27 сентября 2011

Вы можете создать любое представление программно (так как я предполагаю, что вы спрашиваете, как сделать это БЕЗ использования LayoutInflater) и вызвать setView на Toast, который вы сделали.

    //Create a view here
    LinearLayout v = new LinearLayout(this);
    //populate layout with your image and text or whatever you want to put in here

    Toast toast = new Toast(getApplicationContext());
    toast.setGravity(Gravity.CENTER_VERTICAL, 0, 0);
    toast.setDuration(Toast.LENGTH_LONG);
    toast.setView(v);
    toast.show();
12 голосов
/ 08 ноября 2013

Решение Knickedi хорошо, но если вам нужен только значок рядом с текстом, вы можете использовать тот факт, что Toast имеет предопределенный TextView с тем же идентификатором и установить значок в TextView:

Toast toast = Toast.makeText(context, text, Toast.LENGTH_SHORT);
TextView tv = (TextView) toast.getView().findViewById(android.R.id.message);
if (null!=tv) {
    tv.setCompoundDrawablesWithIntrinsicBounds(icon, 0, 0, 0);
    tv.setCompoundDrawablePadding(context.getResources().getDimensionPixelSize(R.dimen.padding_toast));
1 голос
/ 15 апреля 2018
Toast aa = Toast.makeText(getBaseContext(), "OPEN",Toast.LENGTH_SHORT);
ImageView cc = new ImageView(getBaseContext());
cc.setImageResource(R.drawable.a);
aa.setView(cc);
aa.show();
1 голос
/ 14 февраля 2017

Я думаю, что лучше, чтобы мы отображали текст Toast на изображении, которое мы передаем в функцию makeImageToast ... поэтому я оттеняю коды Knickedi и:

public class utility  {

public static Toast makeImageToast(Context context, int imageResId, CharSequence text, int length) {
    Toast toast = Toast.makeText(context, text, length);

    View rootView = toast.getView();
    LinearLayout linearLayout = null;
    View messageTextView = null;

    // check (expected) toast layout
    if (rootView instanceof LinearLayout) {
        linearLayout = (LinearLayout) rootView;

        if (linearLayout.getChildCount() == 1) {
            View child = linearLayout.getChildAt(0);

            if (child instanceof TextView) {
                messageTextView = (TextView) child;
                ((TextView) child).setGravity(Gravity.CENTER);

            }
        }
    }

    // cancel modification because toast layout is not what we expected
    if (linearLayout == null || messageTextView == null) {
        return toast;
    }

    ViewGroup.LayoutParams textParams = messageTextView.getLayoutParams();
    ((LinearLayout.LayoutParams) textParams).gravity = Gravity.CENTER;

    // convert dip dimension
    float density = context.getResources().getDisplayMetrics().density;
    int imageSize = (int) (density * 25 + 0.5f);
    int imageMargin = (int) (density * 15 + 0.5f);

    // setup image view layout parameters
    LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(imageSize, imageSize);
    imageParams.setMargins(0, 0, imageMargin, 0);
    imageParams.gravity = Gravity.CENTER;

    // setup image view
    ImageView imageView = new ImageView(context);
    imageView.setImageResource(imageResId);
    imageView.setLayoutParams(imageParams);


    // modify root layout
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
    linearLayout.setBackgroundResource(imageResId);
    linearLayout.setGravity(Gravity.CENTER);
    linearLayout.setHorizontalGravity(Gravity.CENTER);
    linearLayout.setHorizontalGravity(Gravity.CENTER);
    //addView(imageView, 0);

    return toast;
}

}

и это его использование:

utility.makeImageToast(getApplicationContext(),
                 R.drawable.your_image,"your_text",Toast.LENGTH_LONG).show();
1 голос
/ 25 октября 2011

Всегда есть возможность создать собственный макет.Был один факт, который мне не понравился: он нарушает пользовательский интерфейс системы по умолчанию.Это может отличаться на разных платформах и реализациях.Нет простого способа использовать системный ресурс по умолчанию, поэтому я решил взломать тост и вставить в него изображение.

Подсказка : Вы можете получить ресурс по умолчанию, например:
Toast.makeToast(context, "", 0).getView().getBackground()


Вот помощник, который будет отображать изображение перед тост-сообщением: Helper.makeImageToast(context, R.drawable.my_image, "Toast with image", Toast.LENGTH_SHORT).show()

Я использую это, чтобы указать успех, информацию или ошибку.Делает тост информацию более приятной и выразительной ...

(Стоит отметить, что взлом основан на том факте, что внутренний тост использует LinearLayout, поэтому не зависит от системы и реализации. См. Комментарии.)

public static Toast makeImageToast(Context context, int imageResId, CharSequence text, int length) {
    Toast toast = Toast.makeText(context, text, length);

    View rootView = toast.getView();
    LinearLayout linearLayout = null;
    View messageTextView = null;

    // check (expected) toast layout
    if (rootView instanceof LinearLayout) {
        linearLayout = (LinearLayout) rootView;

        if (linearLayout.getChildCount() == 1) {
            View child = linearLayout.getChildAt(0);

            if (child instanceof TextView) {
                messageTextView = (TextView) child;
            }
        }
    }

    // cancel modification because toast layout is not what we expected
    if (linearLayout == null || messageTextView == null) {
        return toast;
    }

    ViewGroup.LayoutParams textParams = messageTextView.getLayoutParams();
    ((LinearLayout.LayoutParams) textParams).gravity = Gravity.CENTER_VERTICAL;

    // convert dip dimension
    float density = context.getResources().getDisplayMetrics().density;
    int imageSize = (int) (density * 25 + 0.5f);
    int imageMargin = (int) (density * 15 + 0.5f);

    // setup image view layout parameters
    LinearLayout.LayoutParams imageParams = new LinearLayout.LayoutParams(imageSize, imageSize);
    imageParams.setMargins(0, 0, imageMargin, 0);
    imageParams.gravity = Gravity.CENTER_VERTICAL;

    // setup image view
    ImageView imageView = new ImageView(context);
    imageView.setImageResource(imageResId);
    imageView.setLayoutParams(imageParams);

    // modify root layout
    linearLayout.setOrientation(LinearLayout.HORIZONTAL);
    linearLayout.addView(imageView, 0);

    return toast;
}
...