1. 程式人生 > >Android之按鈕

Android之按鈕

Android 按鈕 綁定

本篇關鍵點在於 , 如何為按鈕綁定監聽事件 。一共有3種方法:

現設計UI如下:
技術分享圖片

一 : 第一種方案(在UI中手動指定Btn的處理函數)
① ,在UI中,選中目標button , 修改屬性onClick為onClickOk如下
技術分享圖片
②,在對應界面UI中,定義此函數

    public void onClickOk( View view ){
        CharSequence a = MainActivity.this.txt_t.getText();
        if( a.toString() == "Hello World!" ){
            this.txt_t.setText( "Aonaufly" );
        }else{
            this.txt_t.setText( "Hello World!" );
        }
    }

註意函數必須為public , 返回值必須為void ,參數必須為View

二 : 第二種方案(內部類)
① , 在UI中,選中目標button , 修改屬性onClick為空 , 刪除代碼中onClickOk函數
② ,ui全部代碼如下:

package com.kayer.myfirstdemo;

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

public class MainActivity extends Activity {
    private TextView txt_t = null;
    private Button btn_ok = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.txt_t = (TextView)this.findViewById(R.id.txt_t);
        this.btn_ok = (Button)this.findViewById(R.id.btn_ok);
        this.btn_ok.setOnClickListener( new onOKBtnClick() );
    }
    private class onOKBtnClick implements View.OnClickListener{
        @Override
        public void onClick(View v) {
            CharSequence a = MainActivity.this.txt_t.getText();
            if( a.toString() == "Hello World!" ){
                MainActivity.this.txt_t.setText( "Aonaufly" );
            }else{
                MainActivity.this.txt_t.setText( "Hello World!" );
            }
        }
    }
}

②-1, 顯然需要手動將按鈕(btn_ok)綁定這個內部類(onOKBtnClick)

三 :匿名類,是在第二種方案中進化而來(不用再寫一個內部類)
代碼如下:

package com.kayer.myfirstdemo;

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

public class MainActivity extends Activity {
    private TextView txt_t = null;
    private Button btn_ok = null;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        this.txt_t = (TextView)this.findViewById(R.id.txt_t);
        this.btn_ok = (Button)this.findViewById(R.id.btn_ok);
        this.btn_ok.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                CharSequence a = MainActivity.this.txt_t.getText();
                if( a.toString() == "Hello World!" ){
                    MainActivity.this.txt_t.setText( "Aonaufly" );
                }else{
                    MainActivity.this.txt_t.setText( "Hello World!" );
                }
            }
        });
    }
}

Android之按鈕