平时我们使用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样式,下面是一张效果图