Android教程網
  1. 首頁
  2. Android 技術
  3. Android 手機
  4. Android 系統教程
  5. Android 游戲

Android 教學(五)—— Button 控件搭配 Toast 提示的使用

編輯:關於 Android 程式設計

又到了有空閒的時刻,趁機寫一章教程。本章要學習 Button 控件的使用,同時順帶介紹一下 Toast 提示控件。

在 Android 開發中,我們使用最频繁的用戶交互控件,大概就是 Button 了;而最常用的事件,則莫過於點擊(click)事件。這些都是最基礎的事件,透過 Google 官方提供的 API 就能輕鬆呼叫。具體該怎麼做,我們一步步來看。

第一步:建立工程並設計版面

新建一個名為 Ep.Toast 的工程,Activity 與主版面名稱都採用預設值。版面 activity_main.xml 裡只放一個文字標籤與一個按鈕:

<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:paddingBottom="@dimen/activity_vertical_margin"
    android:paddingLeft="@dimen/activity_horizontal_margin"
    android:paddingRight="@dimen/activity_horizontal_margin"
    android:paddingTop="@dimen/activity_vertical_margin"
    tools:context=".MainActivity" >

    <TextView
        android:id="@+id/textView1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" />

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignTop="@+id/textView1"
        android:layout_marginRight="61dp"
        android:text="確定" />

</RelativeLayout>

第二步:撰寫核心程式 MainActivity.java

這裡我會盡量多加上註解,方便大家理解:

package com.example.ep.toast;

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

public class MainActivity extends Activity {

    private TextView txtview1;
    private Button btn1;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        // 綁定文字標籤控件
        txtview1 = (TextView) findViewById(R.id.textView1);
        // 綁定按鈕控件
        btn1 = (Button) findViewById(R.id.button1);
        // 為按鈕加入點擊事件監聽器
        btn1.setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                // 點擊按鈕後設定文字標籤內容
                txtview1.setText("Joven");
                // 點擊按鈕後彈出提示框,參數依序為(綁定的 Activity、提示內容、顯示時間)
                Toast.makeText(MainActivity.this, "Joven", Toast.LENGTH_LONG).show();
            }
        });
    }
}

透過 setOnClickListener() 為按鈕掛上監聽器,在使用者點擊時便會觸發 onClick()。其中 Toast.makeText() 的三個參數分別是:綁定的 Activity、要顯示的文字,以及顯示時長(Toast.LENGTH_LONG 或 Toast.LENGTH_SHORT)。這些看似再基礎不過的東西,其實正是日後龐大複雜專案的基石——知識都是靠日積月累才會沉澱成精華。

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