Добавление изображения в Тост?
можно ли программно добавить рисунок в всплывающее окно?
7 ответов
Да, вы можете добавить imageview или любое представление в уведомление тоста с помощью метода setView (), используя этот метод, вы можете настроить тост в соответствии с вашим требованием.
здесь я создал пользовательский файл макета для раздувания в уведомление тоста, а затем я использовал этот макет в уведомлении тоста с помощью 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();
просто используйте следующее:
Toast toast = new Toast(myContext);
ImageView view = new ImageView(myContext);
view.setImageResource(R.drawable.image_icon);
toast.setView(view);
toast.show();
вы можете создать любое представление программно (так как я предполагаю, что вы спрашиваете, как это сделать без использования 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();
решение Knickedi хорошо, но если вам нужен только значок рядом с текстом, Вы можете использовать тот факт, что тост имеет предварительно определенный 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));
всегда есть возможность создать пользовательский макет. Был один факт, который мне не понравился: он нарушает системный пользовательский интерфейс тостов по умолчанию. Это может отличаться на разных платформах и реализациях. Нет простого способа использовать системный ресурс по умолчанию, поэтому я решил взломать тост и заставить изображение в него.
подсказка: вы можете получить ресурс по умолчанию такой: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;
}
Я думаю, что лучше показать текст тоста На изображении, которое мы передаем функции 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();
Toast aa = Toast.makeText(getBaseContext(), "OPEN",Toast.LENGTH_SHORT);
ImageView cc = new ImageView(getBaseContext());
cc.setImageResource(R.drawable.a);
aa.setView(cc);
aa.show();