Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲
您现在的位置: Android教程網 >> Android系統教程 >  >> Android 技術 >> Android 開發實例

Android 入門教程(八):Button 點擊事件與 Toast 提示的組合應用

編輯:Android 開發實例

上一節我們學會了在 main.xml 裡定義 Button,這一節來看它如何響應點擊,並順帶用上提示元件 Toast。

按鈕的事件處理在 Android 中由 Button.OnClickListener 負責,寫過 Java 的人對 OnXxxListener 這類命名應該不陌生。範例的效果是:點下按鈕後,TextView 的文字改變,同時畫面下方浮出一段持續片刻的 Toast 提醒。

[點擊前效果圖]

[點擊後效果圖]

一、版面檔 main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="https://schemas.android.com/apk/res/android"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:orientation="vertical">

    <TextView
        android:id="@+id/textview1"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/hello" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="right"
        android:text="確定" />
</LinearLayout>

兩個細節值得說明:android:id 是讓 Java 端能用 findViewById() 找到這個控件;android:layout_gravity="right" 讓按鈕靠右對齊。

二、主程式 ButtonDemo.java

package com.android.test;

import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
import android.widget.Toast;

public class ButtonDemo extends Activity {

    private TextView textview1;
    private Button button1;

    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        // 透過 id 取得 main.xml 裡定義的 TextView 與 Button
        textview1 = (TextView) findViewById(R.id.textview1);
        button1 = (Button) findViewById(R.id.button1);

        // 掛上點擊事件
        button1.setOnClickListener(new Button.OnClickListener() {
            public void onClick(View v) {
                // Toast 提示
                Toast.makeText(ButtonDemo.this,
                        "TextView 裡的文字改變了,你注意到了嗎?",
                        Toast.LENGTH_LONG).show();

                // 改變 TextView 的文字
                textview1.setText("歡迎來到魏祝林的部落格!");
            }
        });
    }
}

Toast 的兩個常用參數

Toast.makeText(context, text, duration) 的第三個參數只有兩種選擇:Toast.LENGTH_SHORT(約 2 秒)與 Toast.LENGTH_LONG(約 3.5 秒)。它不會搶走焦點、不能攔截點擊,因此適合傳達「不中斷操作」的訊息;若需要使用者明確回應,該用的是 Dialog。

寫法上還有個小差異:除了匿名內部類,也可以讓 Activity 直接實作 OnClickListener,或是使用 Java 8 之後的 Lambda 寫法(需相應的編譯設定)。三者效果相同,選團隊一致的寫法即可。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © Android教程網 All Rights Reserved