1、得到布局文件中的空间句柄
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
<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>
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帮助文档