- 掌握事件的处理方法。
- 掌握组件间的数据传递方法。
- 掌握数据回传的方法。
- 分别用四种方式实现事件的处理。
方法一、定义事件监听器,再与组件绑定
button = (Button)findViewById(R.id.button11);①获取代表监听器的对象
textView = (TextView)findViewById(R.id.text11);
ButtonClickListener listener = new ButtonClickListener();④生成监听器
button.setOnClickListener(listener);⑤绑定监听器
②定义一个类,实现监听器接口
class ButtonClickListener implements View.OnClickListener{
@Override
public void onClick(View view) {
textView.setTextColor(Color.CYAN );
textView.setTextSize(24);③点击后字体大小为24,颜色为CYAN
}
}
方法二、在与组件绑定时定义事件监听器
button2 = (Button)findViewById(R.id.button2);
textView2 = (TextView)findViewById(R.id.text2);
生成监听器并且绑定监听器
button2.setOnClickListener(new View.OnClickListener(){
@Override
public void onClick(View view) {
textView2.setTextColor(Color.BLUE);点击后字体大小为40,颜色为BLUE
textView2.setTextSize(40);
}
});
方法三、在当前Activity实现监听接口
button3 = (Button)findViewById(R.id.button3);
textView3 =(TextView)findViewById(R.id.text3);
button3.setOnClickListener(this);当前Activity实现监听接口
public void onClick(View v){
textView3.setTextSize(40);
textView3.setTextColor(Color.GREEN);点击后字体大小为40,颜色为GREEN
}
方法四、在XML布局文件中设置回调方法名
<Button
android:id="@+id/button4"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="buttonClick"回调方法名
android:text="点击4"/>
button4 = (Button)findViewById(R.id.button4);
textView4 =(TextView)findViewById(R.id.text4);
public void buttonClick(View v){
textView4.setTextColor(Color.BLUE);
textView4.setTextSize(50);点击后字体大小为50,颜色为BLUE
}