public class TestToastActivity extendsAppCompatActivity {privateButton mBtnApple;privateButton mBtnBanana;privateToast toast;privateLayoutInflater inflater;privateView view;privateImageView Iv;privateTextView Tv;
@Overrideprotected voidonCreate(Bundle savedInstanceState) {super.onCreate(savedInstanceState);
setContentView(R.layout.activity_test_toast);
toast= newToast(getApplicationContext());
inflater= LayoutInflater.from(TestToastActivity.this);
view= inflater.inflate(R.layout.toast, null);
Iv= view.findViewById(R.id.toast_image_view);//找到 toast.xml 中 ImageView 控件的 id
Tv = view.findViewById(R.id.toast_text_view);//找到 toast.xml 中 TextView 控件的 id
mBtnApple=findViewById(R.id.btn_apple);
mBtnBanana=findViewById(R.id.btn_banana);
mBtnApple.setOnClickListener(newView.OnClickListener() {
@Overridepublic voidonClick(View v) {
Iv.setImageResource(R.mipmap.apple_96px);
Tv.setText("Apple");
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);
toast.setGravity(Gravity.CENTER,0, 0);//将该toast居中显示
toast.show();
}
});
mBtnBanana.setOnClickListener(newView.OnClickListener() {public voidonClick(View v) {
Iv.setImageResource(R.mipmap.banana_96px);
Tv.setText("Banana");
toast.setView(view);
toast.setDuration(Toast.LENGTH_SHORT);//Toast 显示的时长
toast.setGravity(Gravity.CENTER, 0, 0);//将该toast居中显示
toast.show();
}
});
}
}