Подтвердить что ты не робот

Добавление изображения в Toast?

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

4b9b3361

Ответ 1

Да, вы можете добавить изображение или любое представление в уведомление тоста с помощью метода 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();

Ответ 2

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

Toast toast = new Toast(myContext);
ImageView view = new ImageView(myContext); 
view.setImageResource(R.drawable.image_icon); 
toast.setView(view); 
toast.show();

Ответ 3

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

    //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();

Ответ 4

Решение 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));

Ответ 5

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

Подсказка: вы можете получить ресурс по умолчанию следующим образом: 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;
}

Ответ 6

Я думаю, что это лучше, если мы покажем текст 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();