ToastActivity.java文件:
1 public class ToastActivity extends AppCompatActivity { 2 private Button mbtnToast1,mbtnToast2,mbtnToast3; 3 @Override 4 protected void onCreate(Bundle savedInstanceState) { 5 super.onCreate(savedInstanceState); 6 setContentView(R.layout.activity_toast); 7 mbtnToast1=findViewById(R.id.btn_toast1); 8 mbtnToast2=findViewById(R.id.btn_toast2); 9 mbtnToast3=findViewById(R.id.btn_toast3); 10 OnClick onClick=new OnClick(); 11 mbtnToast1.setOnClickListener(onClick); 12 mbtnToast2.setOnClickListener(onClick); 13 mbtnToast3.setOnClickListener(onClick); 14 } 15 16 class OnClick implements View.OnClickListener{ 17 18 @Override 19 public void onClick(View view) { 20 switch (view.getId()){ 21 case R.id.btn_toast1: 22 Toast.makeText(getApplicationContext(), "点击一", Toast.LENGTH_SHORT).show(); 23 break; 24 case R.id.btn_toast2: 25 Toast toastCenter=Toast.makeText(getApplicationContext(),"点击二居中显示",Toast.LENGTH_SHORT); 26 toastCenter.setGravity(Gravity.CENTER,0,0); 27 toastCenter.show(); 28 break;//使提示框居中显示 29 case R.id.btn_toast3: 30 Toast toastCustom=new Toast(getApplicationContext()); 31 LayoutInflater inflater=LayoutInflater.from(ToastActivity.this); 32 View view1 = inflater.inflate(R.layout.layout_toast, null); 33 ImageView imageView=view.findViewById(R.id.iv_toast); 34 TextView textView=view.findViewById(R.id.tv_toast); 35 imageView.setImageResource(R.drawable.zidingyi); 36 textView.setText("点击三自定义提示框出现"); 37 toastCustom.setView(view1); 38 toastCustom.setDuration(Toast.LENGTH_SHORT); 39 toastCustom.show(); 40 break;//没搞出来,自定义的对话框 41 } 42 } 43 } 44 }
然后对应activity_toast.xml文件:
1 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 2 android:layout_width="match_parent" 3 android:layout_height="match_parent" 4 android:orientation="vertical"> 5 6 <Button 7 android:id="@+id/btn_toast1" 8 android:layout_width="match_parent" 9 android:layout_height="wrap_content" 10 android:text="默认"/> 11 12 <Button 13 android:id="@+id/btn_toast2" 14 android:layout_width="match_parent" 15 android:layout_height="wrap_content" 16 android:text="改变提示框出现位置"/> 17 18 <Button 19 android:id="@+id/btn_toast3" 20 android:layout_width="match_parent" 21 android:layout_height="wrap_content" 22 android:text="自定义(带图片)"/> 23 24 </LinearLayout>
其实还有一个layout_toast.xml文件来定义自定义提示框的,但是没搞出来 ,就不放了,不知道是啥子原因。