【问题标题】:Adding image to Toast?向 Toast 添加图像?
【发布时间】:2011-11-26 04:19:45
【问题描述】:

是否可以以编程方式将图像添加到 toast 弹出窗口?

【问题讨论】:

标签: android android-toast


【解决方案1】:

您可以以编程方式创建任何视图(因为我假设您询问如何在不使用 LayoutInflater 的情况下执行此操作)并在您制作的 Toast 上调用 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();

【讨论】:

    【解决方案2】:

    是的,您可以使用 setView() 方法将 imageview 或任何视图添加到 toast 通知中,使用此方法您可以根据需要自定义 Toast。

    在这里,我创建了一个自定义布局文件以填充到 Toast 通知中,然后我通过 setView() 方法在 Toast 通知中使用了此布局。

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

    【讨论】:

    • @Blundell Here 是带有输出快照的详细教程。
    【解决方案3】:

    始终可以创建自定义布局。有一个我不喜欢的事实:它破坏了系统默认的 toast UI。这在不同的平台和实现上可能会有所不同。使用系统默认资源没有简单的方法,所以我决定破解 toast 并强制将图像放入其中。

    提示:你可以像这样获取默认资源:
    Toast.makeToast(context, "", 0).getView().getBackground()


    这是一个帮助器,它将在 toast 消息前显示图像: Helper.makeImageToast(context, R.drawable.my_image, "Toast with image", Toast.LENGTH_SHORT).show()

    我用它来表示成功、信息或错误。使吐司信息更好,更具表现力...

    (值得一提的是,黑客基于内部 toast 使用 LinearLayout 的事实,因此不是系统和实现独立的。请参阅 cmets。)

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

    【讨论】:

    • 这仅适用于 Toast 的布局类型为 LinearLayout 的情况。没有联系 afaik,Toast 将始终具有 LinearLayout。您的代码通过不添加图像来处理此问题,但值得注意的是此解决方案与设备/版本无关。
    • @Graeme 你是对的。谢谢你的提示。更好的方法是在自己的 LinearLayout 中重新创建 toast。当我找到一些时间时,我会更新我的答案。
    【解决方案4】:

    简单地说,使用以下内容:

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

    【讨论】:

      【解决方案5】:

      Knickedi 的解决方案很好,但是如果您只需要文本旁边的图标,您可以利用 Toast 具有相同 ID 的预定义 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));
      

      【讨论】:

        【解决方案6】:

        我认为我们在传递给 makeImageToast 函数的图像上显示 Toast 文本会更好... 所以我给 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();
        

        【讨论】:

          【解决方案7】:
          Toast aa = Toast.makeText(getBaseContext(), "OPEN",Toast.LENGTH_SHORT);
          ImageView cc = new ImageView(getBaseContext());
          cc.setImageResource(R.drawable.a);
          aa.setView(cc);
          aa.show();
          

          【讨论】:

          • 虽然理论上这可以回答问题,但it would be preferable 描述了您解决方案的基本部分。这似乎与之前的答案几乎相同。
          【解决方案8】:
              class CustomToast extends AppCompatActivity {
              Button custom_toast;
          
              @Override
              protected void onCreate(Bundle savedInstanceState) {
                  super.onCreate(savedInstanceState);
                  setContentView(R.layout.activity_custom_toast);
          
                  custom_toast = (Button) findViewById(R.id.customToast);
                  custom_toast.setOnClickListener(new View.OnClickListener() {
                      @Override
                      public void onClick(View v) {
                          LayoutInflater inflater=getLayoutInflater();
                          View layout=inflater.inflate(R.layout.custom_toast_layout, (ViewGroup) findViewById(R.id.toast_layout_root));
          
                          TextView toastTextView=(TextView) findViewById(R.id.toastTextView);
                          ImageView toastimageview=(ImageView) findViewById(R.id.toastImageView);
                          toastTextView.setText("Custom toast in android");
                          toastimageview.setImageResource(R.drawable.ic_launcher_background);
          
                          Toast toast=new Toast(CustomToast.this);
                          toast.setDuration(Toast.LENGTH_SHORT);
                          toast.setView(layout);
                          toast.show();
                      }
                  });
              }
          }
          

          【讨论】:

            猜你喜欢
            • 2012-02-26
            • 2015-08-06
            • 1970-01-01
            • 1970-01-01
            • 2014-07-22
            • 2013-01-19
            • 2018-01-28
            • 2014-09-05
            • 2020-05-19
            相关资源
            最近更新 更多