自定义Toast实现自定义Toast布局

平时我们使用Toast的时候都是这样的一种方法

Toast toast = Toast.makeText(context, "", duration);

现在我们来自定义下Toast的布局,首先看下Toast创建时的源代码

 public static Toast makeText(Context context, CharSequence text, @Duration int duration) {
        Toast result = new Toast(context);

        LayoutInflater inflate = (LayoutInflater)
                context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflate.inflate(com.android.internal.R.layout.transient_notification, null);
        TextView tv = (TextView)v.findViewById(com.android.internal.R.id.message);
        tv.setText(text);
        
        result.mNextView = v;
        result.mDuration = duration;

        return result;
    }    
很清楚的一段代码,Toast的创建其实是调用了系统已经创建好了一个布局文件com.android.internal.R.layout.transient_notification
然后找到控件设置要显示的数据。Toast类的内部有有一个方法如下。我们可以利用这个方法覆盖Toast的原有布局。

public void setView(View view) {
        mNextView = view;
    }

下面是我简单的写的一个自定义布局显示Toast方法,首先就要创建一个Toast,这时Toast内部的mNextView布局其实已经创建完毕,然后我们利用上
面的的setView方法覆盖这个布局达到自定义的效果。

public void show(){
        Toast toast=Toast.makeText(this,"",Toast.LENGTH_LONG);
        LinearLayout linearLayout=new LinearLayout(this);
        linearLayout.setOrientation(LinearLayout.VERTICAL);
        linearLayout.removeAllViews();
        TextView textView1=new TextView(this);
        textView1.setText("Toast1");
        TextView textView2=new TextView(this);
        textView2.setText("Toast1");
        linearLayout.addView(textView1);
        linearLayout.addView(textView2);
        ImageView imageView=new ImageView(this);
        imageView.setImageDrawable(ContextCompat.getDrawable(this,R.mipmap.ic_launcher));
        linearLayout.addView(imageView);
        linearLayout.setBackground(toast.getView().getBackground());
        toast.setView(linearLayout);
        toast.show();
    }
这样是写简单的布局,当然你可以随心所欲的设置你想要的Toast样式,下面是一张效果图














  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值