1. 使用内部类实现事件监听器的步骤
- 第一步(定义成员变量):将内部类中要控制的组件定义为当前的Activity的成员变量
- 第二步(获取组件):在当前Activity的onCreate()方法中获取需要的组件
- 第三步(定义内部类):在当前的Activity中定义内部类成员,并编写事件处理器代码
- 第四步(创建监听器):在当前Activity的onCreate()方法中创建监听器
- 第五步(为事件源注册监听器):在当前Activity的onCreate()方法中为事件源注册监听器
2.如
Layout下的activity_main_xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/test"
android:text="测试文字"
android:layout_marginTop="20dp"
android:layout_gravity="center_horizontal"/>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_margin="10dp"
android:gravity="center_horizontal">
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/red"
android:text="红色" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/green"
android:text="绿色"
android:layout_marginLeft="10dp"/>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/blue"
android:text="蓝色"
android:layout_marginLeft="10dp"/>
</LinearLayout>
</LinearLayout>
测试界面布局
MainActivity.java下的代码
import androidx.appcompat.app.AppCompatActivity;
import android.graphics.Color;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;
public class MainActivity extends AppCompatActivity {
private TextView test; //定义成员变量
private Button red, green, blue; //定义成员变量
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
test=(TextView) findViewById(R.id.test); //获取组件
red=(Button) findViewById(R.id.red);
green=(Button) findViewById(R.id.green);
blue=(Button) findViewById(R.id.blue);
InterLinsten interLinsten=new InterLinsten();//创建监听器
red.setOnClickListener(interLinsten); //注册监听器
blue.setOnClickListener(interLinsten);
green.setOnClickListener(interLinsten);
}
//定义内部类InterLinsten实现(implement)事件响应
private class InterLinsten implements View.OnClickListener{
@Override
public void onClick(View v) {
switch (v.getId()) {
case R.id.red:
test.setTextColor(Color.RED);
break;
case R.id.blue:
test.setTextColor(Color.BLUE);
break;
case R.id.green:
test.setTextColor(Color.GREEN);
default:break;
}
}
}
}