Android Studio 之 在活動中使用 Toast


 

•簡介

  Toast 是 Android 系統提供的一種非常好的提醒方式;

  在程序中可以使用它將一些短小的信息通知給用戶;

  這些信息會在一段時間內自動消失,並且不會占用任何屏幕空間

•Toast.makeText()函數原型

  Toast.makeText(參數1,參數2,參數3); 

  • 參數1是 Context,是 Toast 要求的上下文

    • 由於活動本身就是一個Context對象,因此直接傳入 XXXActivity.this 即可,或者填入 getApplicationContext()  
  • 參數2是 Toast 顯示的文本內容

  • 參數3是 Toast 顯示的時長,有兩個內置常量可以選擇  Toast.LENGTH_SHORT  和  Toast.LENGTH_LONG 

•准備工作

  新建一個項目,並選擇 Empty Activity;

  這樣,Android Studio 為我們自動生成了 MainActivity.java 和 activity_main.xml 文件;

  修改 activity_mian.xml 中的代碼;

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"
    android:padding="10dp">

    <Button
        android:id="@+id/btn_1"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#33CCCC"
        android:text="Button_1" />

    <Button
        android:id="@+id/btn_2"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginTop="10dp"
        android:background="#D54D2B"
        android:text="Button_2" />
</LinearLayout>

  在該布局中,定義了兩個 Button;

  想要使用 Toast,需要定義一個彈出 Toast 的觸發點;

  正好我們定義了兩個 Button,那我們就讓點擊 Button 的時候彈出一個 Toast 吧;

  有兩種方式定義 Button 的點擊事件:

  • 用匿名類來實現點擊事件的方法

  • 用外部類來實現點擊事件的代碼如下

•用匿名類來實現點擊事件

  修改 MainActivity.java 中的代碼;

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//給當前的活動加載一個布局
        Button btn1 = findViewById(R.id.btn_1);

        //用匿名類來實現點擊事件的方法
        btn1.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(MainActivity.this, "Button_1", Toast.LENGTH_SHORT).show();
            }
        });
    }
}

•運行效果

  

•用外部類來實現點擊事件

  修改 MainActivity.java 中的代碼;

MainActivity.java

public class MainActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//給當前的活動加載一個布局
        Button btn2 = findViewById(R.id.btn_2);
        btn2.setOnClickListener(new MyClick());
    }

    //用外部類來實現點擊事件的代碼如下
    class MyClick implements View.OnClickListener {

        @Override
        public void onClick(View v) {
            Toast t = Toast.makeText(MainActivity.this, "Button_2", Toast.LENGTH_SHORT);
            t.show();
        }
    }
}

  當然,你也可以這么寫;

public class MainActivity extends AppCompatActivity implements View.OnClickListener{

    @Override
    protected void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);//給當前的活動加載一個布局
        Button btn2 = findViewById(R.id.btn_2);
        btn2.setOnClickListener(this);
    }


    @Override
    public void onClick(View v) {
        Toast t = Toast.makeText(MainActivity.this, "Button_2", Toast.LENGTH_SHORT);
        t.show();
    }
}

   讓 MainActivity 實例化 View.OnClickListener 接口,並重寫  onClick() 方法;

•運行效果

  

 

•小結

  在活動中,通過  findViewById() 方法獲取到在布局文件中定義的元素;

  得到按鈕實例后,我們通過  setOnClickListener() 方法為按鈕注冊一個監聽器;

  點擊按鈕就會執行監聽器中的  onClick() 方法;

  因此將點擊按鈕彈出 Toast 的功能編寫在  onClick() 方法中;

  Toast 的用法非常簡單,通過靜態方法  makeText() 創建出一個 Toast 對象;

  然后調用  show() 方法將 Toast 顯示出來即可;

•自定義 Toast

  首先,在 layout 文件夾下自定義一個 .xml 文件,並命名為 toast.xml;

  在里面放入如下代碼:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:layout_gravity="center">


    <com.example.uibestpractice.CircleImageView
        android:id="@+id/toast_image_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:scaleType="centerInside" />

    <TextView
        android:id="@+id/toast_text_view"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_below="@id/toast_image_view"
        android:layout_centerHorizontal="true"
        android:gravity="center"
        android:textColor="@color/black"
        android:textSize="15sp" />
</RelativeLayout>

  其中的 <CircleImageView> 控件是我之前自定義的圓形 ImageView,詳情見我這篇博客

  然后,新建一個 Empty Activity ,命名為 TestTostActivity;

  這樣Android Studio自動為我們生成了 TestToastActivity.java 和 activity_test_toast.xml;

  在 activity_test_toast.xml 中添加如下代碼:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@color/blue"
    android:padding="10dp">

    <TextView
        android:id="@+id/tv"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="測試自定義 Toast"
        android:textSize="20sp"
        android:textColor="@color/black"/>

    <LinearLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:orientation="horizontal">

        <Button
            android:id="@+id/btn_apple"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Apple"/>

        <Button
            android:id="@+id/btn_banana"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Banana" />
    </LinearLayout>
</RelativeLayout>

  在 TestToastActivity.java 中設置相應的點擊事件,並設置  Toast,代碼如下:

public class TestToastActivity extends AppCompatActivity {

    private Button mBtnApple;
    private Button mBtnBanana;
    private Toast toast;
    private LayoutInflater inflater;
    private View view;
    private ImageView Iv;
    private TextView Tv;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_test_toast);

        toast = new Toast(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(new View.OnClickListener() {

            @Override
            public void onClick(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(new View.OnClickListener() {

            public void onClick(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();
            }
        });
    }
}

•運行效果

  

•聲明

  參考資料:

  【AndroidStudio自定義Toast及其用法

  【Android Studio 在活動中使用Toast

 

MainActivity


免責聲明!

本站轉載的文章為個人學習借鑒使用,本站對版權不負任何法律責任。如果侵犯了您的隱私權益,請聯系本站郵箱yoyou2525@163.com刪除。



 
粵ICP備18138465號   © 2018-2025 CODEPRJ.COM