在xml中通过onClick设置一个事件处理方法,然后需要在Activity中定义该方法。
主代码:
public class MainActivity extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
//定义一个事件处理方法
//source参数代表事件源
public void clickHandler(View source ) {
EditText show=(EditText) findViewById(R.id.show);
show.setText("按钮被单击了");
}
}
主布局:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<EditText
android:id="@+id/show"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:cursorVisible="false"
android:editable="false" />
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:onClick="clickHandler"
android:text="单击我" />
</LinearLayout>
运行效果: