本篇关键点在于 , 如何为按钮绑定监听事件 。一共有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!" ); } } }); }}