Android Toast三种使用方法
例题2-15
activiy_main.xml代码
1 <?xml version="1.0" encoding="utf-8"?> 2 <LinearLayout android:layout_width="fill_parent" 3 android:layout_height="fill_parent" 4 android:orientation="vertical" 5 xmlns:android="http://schemas.android.com/apk/res/android"> 6 <Button 7 android:id="@+id/btn1" 8 android:layout_width="200dip" 9 android:layout_height="wrap_content" 10 android:layout_gravity="center" 11 android:text="默认方式"/> 12 <Button 13 android:id="@+id/btn2" 14 android:layout_width="200dip" 15 android:layout_height="wrap_content" 16 android:layout_gravity="center" 17 android:text="自定义方式"/> 18 <Button 19 android:id="@+id/btn3" 20 android:layout_width="200dp" 21 android:layout_height="wrap_content" 22 android:layout_gravity="center" 23 android:text="图片方式"/> 24 </LinearLayout>
Mainactivity.java代码
1 package com.example.hellos; 2 3 import androidx.appcompat.app.AppCompatActivity; 4 5 import android.os.Bundle; 6 import android.view.Gravity; 7 import android.view.View; 8 import android.widget.Button; 9 import android.widget.GridLayout; 10 import android.widget.ImageView; 11 import android.widget.LinearLayout; 12 import android.widget.Toast; 13 14 public class MainActivity extends AppCompatActivity { 15 Button b1,b2,b3; 16 Toast toast; 17 LinearLayout toastView; 18 ImageView imageView; 19 @Override 20 protected void onCreate(Bundle savedInstanceState) { 21 super.onCreate(savedInstanceState); 22 setContentView(R.layout.activity_main); 23 b1=(Button)findViewById(R.id.btn1); 24 b2=(Button)findViewById(R.id.btn2); 25 b3=(Button)findViewById(R.id.btn3); 26 b1.setOnClickListener(new myClick()); 27 b2.setOnClickListener(new myClick()); 28 b3.setOnClickListener(new myClick()); 29 30 } 31 32 private class myClick implements View.OnClickListener { 33 34 @Override 35 public void onClick(View v) { 36 if(v==b1){ 37 Toast.makeText(MainActivity.this,"Toast",Toast.LENGTH_SHORT).show(); 38 }else if(v==b2){ 39 toast=Toast.makeText(MainActivity.this,"toast",Toast.LENGTH_SHORT); 40 toast.setGravity(Gravity.CENTER,0,0); 41 toast.show(); 42 }else{ 43 toast=Toast.makeText(MainActivity.this,"toast",Toast.LENGTH_SHORT); 44 toast.setGravity(Gravity.CENTER,0,80); 45 toastView=(LinearLayout)toast.getView(); 46 imageView=new ImageView(MainActivity.this); 47 imageView.setImageResource(R.drawable.p1); 48 toastView.addView(imageView,0); 49 toast.show(); 50 } 51 } 52 } 53 }