自定义Toast时:This Toast was not created with Toast.makeText()

289 阅读1分钟

在使用自定义Toast时候,我们不能直接使用toast.setText()方法来设置显示信息;我们需要使用TextView来显示信息。

public void getToast(int pic,String msg) {
        Toast toast = new Toast(this);
        ImageView imageView = new ImageView(this);
        imageView.setImageResource(pic);
        TextView textView = new TextView(this);
        textView.setText(msg);
        LinearLayout linearLayout = new LinearLayout(this);
        linearLayout.setHorizontalGravity(LinearLayout.HORIZONTAL);
        linearLayout.addView(imageView);
        linearLayout.addView(textView);
        //toast.setText("1"); 错误
        toast.setView(linearLayout);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.show();
    }

也可以通过创建layout布局来设置自定义Toast的样式,布局文件自己创建哈,如下:

public void getToast(int pic, String msg) {
        Toast toast = new Toast(this);
        LayoutInflater inflater = LayoutInflater.from(this);
        View layout = inflater.inflate(R.layout.toast_info, null, false);
        ImageView toastImage = layout.findViewById(R.id.toastImage);
        toastImage.setImageResource(pic);
        TextView toastTv = layout.findViewById(R.id.toastTv);
        toastTv.setText(msg);
        toast.setView(layout);
        toast.setDuration(Toast.LENGTH_SHORT);
        toast.show();
    }

 

暑期编程PK赛

得CSDN机械键盘等精美礼品!