[Android]事件响应

本文介绍如何在Android中通过findViewById获取布局文件中的控件句柄,并使用setOnClickListener等方法为Button设置点击事件来改变TextView的背景颜色。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

1、得到布局文件中的空间句柄  

View android.app. Activity.findViewById( int id)

2、设置控件的行为

控件的void android.view. View.setOnClickListener( OnClickListener l)等接口
类似的接口有SetXXXListener等

activity_main.xml

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:id="@+id/screen"    
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical"  >

    <TextView
        android:id="@+id/txt"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/hello_world" 
        android:layout_gravity="center"/>
    
     <Button
        android:id="@+id/Bt1"       
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/red" 
        android:layout_gravity="center"/>
     
     <Button
        android:id="@+id/Bt2"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="@string/green" 
        android:layout_gravity="center"/>

</LinearLayout>

    .Java

final TextView txt = (TextView)findViewById(R.id.txt);
Button   bt1 = (Button)findViewById(R.id.Bt1);
Button   bt2 = (Button)findViewById(R.id.Bt2);
		
bt1.setOnClickListener(new OnClickListener(){

@Override
public void onClick(View v) {
	txt.setBackgroundColor(Color.RED);				
}
			
});
		
		bt2.setOnClickListener(new OnClickListener(){

			@Override
			public void onClick(View v) {
				txt.setBackgroundColor(Color.GREEN);				
			}
			
		});

 android:id="@+id/txt"

在xml中定义了android,则可以通过FindViewById(id)找到控件的句柄


Button的setOnClickListener要求参数为OnClickListener,且必须实现onClick接口,这里实现的onClick比较简单,直接给TextView设置颜色,当然,这里可以根据实际情况作出不同的响应

当前点击red按钮时,会将文本背景设置为红色


SetOnXXXListener()等函数是android.view.View类的接口,各种控件(Button,TextView)都继承自此类,其他类似的接口还有:

public void setOnFocusChangeListener (View.OnFocusChangeListener l)
public void setOnGenericMotionListener (View.OnGenericMotionListener l)
public void setOnKeyListener (View.OnKeyListener l)
public void setOnLongClickListener (View.OnLongClickListener l)
等,具体可参考Android帮助文档


评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值