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

蝸牛筆記:Android 基礎之按鈕監聽器

編輯:關於 Android 程式設計

這是一個最基礎的範例:在 XML 佈局中放入一個 TextView 和一個按鈕,並透過監聽器讓按鈕在被點擊時改變文字的顯示內容。

XML 佈局檔

     

Java 程式碼

package com.wjj.day_01_genesis; import android.app.Activity; import android.graphics.Color; import android.os.Bundle; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.TextView; public class MainActivity extends Activity { private TextView textView; private Button button; int count = 0; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); // 設置布局文件 textView = (TextView) findViewById(R.id.textView); // 找到文本 textView.setBackgroundColor(Color.BLUE); // 設置文本背景的顏色 button = (Button) findViewById(R.id.button); // 找到按鈕 buttonOnClickLisnter lisnter = new buttonOnClickLisnter(); // 初識化一個監聽器 button.setOnClickListener(lisnter); // 給按鈕設置監聽器 } class buttonOnClickLisnter implements OnClickListener { // 實現OnClickListener接口 @Override public void onClick(View view) { // 當綁定此監聽器的按鈕被按下時會調用此方法 // TODO Auto-generated method stub count++; textView.setText(count + ""); // 設置文本的顯示 } } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().inflate(R.menu.main, menu); return true; } } 

重點說明:先透過 findViewById 找到 TextView 與 Button,並用 setBackgroundColor 把文字背景設為藍色;接著建立一個實作了 OnClickListener 介面的監聽器物件,用 setOnClickListener 綁定到按鈕上。當按鈕被點擊時,onClick 方法便會被觸發,此時計數器 count 累加,並把最新的數字顯示到 TextView 上。這就是最典型的「按鈕點擊事件」處理流程。

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