按钮响应事件
本例子介绍在Android中几种基本的程序控制方法,要获得的效果是通过2个按钮来控制一个文本框的背景颜色,其运行结果如图所示

本例构建一个应用程序,其在AndroidManifest.xml描述文件中的内容如下所示:
<activity android:name="TestEvent1" android:label="TestEvent1">
<intent-filter>
<action android:name="android.intent.action.MAIN"/>
<category android:name="android.intent.category.LAUNCHER"/>
</intent-filter>
</activity>
布局文件(layout)的代码:
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/screen"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical">
<TextView android:id="@+id/text1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:textSize="24sp"
android:text="@string/text1" />
<Button android:id="@+id/button1"
android:layout_width="80sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/red"/>
<Button android:id="@+id/button2"
android:layout_width="80sp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:text="@string/green"/>
</LinearLayout>
根据以上的布局文件中定义的两个按钮和一个文本框,这个布局文件被活动设置为View后,显示的内容就如上图所示,只是行为还没有实现。 行为将在源代码文件TestEvent1.java中实现,这部分的代码如下所示:
public class TestEvent1 extends Activity {
private static final String TAG = "TestEvent1";
public TestEvent1() { }
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testevent);
final TextView Text = (TextView) findViewById(R.id.text1); // 获得句柄
final Button Button1 = (Button) findViewById(R.id.button1);
final Button Button2 = (Button) findViewById(R.id.button2);
Button1.setOnClickListener(new OnClickListener() { // 实现行为功能
public void onClick(View v) {
Text.setBackgroundColor(Color.RED);
}
});
Button2.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
Text.setBackgroundColor(Color.GREEN);
}
});
}
}
在创建的过程中,通过findViewById获得各个屏幕上面的控件(控件)的背景,这里使用的R.id.button1等和布局文件中各个元素的id是对应的。实际上,在布局文件中,各个控件即使不写android:id这一项也可以正常显示,但是如果需要在代码中进行控制,则必须设置这一项。 根据Button 控件的setOnClickListener()设置了其中的点击行为,这个方法的参数实际上是一个View.OnClickListener类型的接口,这个接口需要被实现才能够使用,因此在本例的设置中,实现了其中的onClick()函数。这样既可实现点击的时候实现相应的功能在点击的函数中将通过Text的句柄对其进行控制。
浙公网安备 33010602011771号