Android button事件处理方式


在Android1.6版本及以后的版本中提供了,对于button的事件处理提供了一种更加简单的机制。通过在布局文件<button>标签中配置android:click属性,同时在代码部分编写想对应的代码即可实现其事件的处理,这样大大简化了代码量,同时便于程序的维护与扩展。

请看代码:

布局文件test.xml

<LinearLayout android:id="@+id/LinearLayout01" android:layout_width="fill_parent" android:layout_height="fill_parent" xmlns:android="http://schemas.android.com/apk/res/android" android:orientation="vertical">
<Button android:text="@+id/Button01" android:id="@+id/Button01" android:layout_width="wrap_content" android:layout_height="wrap_content" android:onClick="myClick"></Button>
</LinearLayout>
程序代码:
public class TestActivity extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.test);
}
public void myClick(View target){
switch(target.getId()){
case R.id.Button01:
Log.i("--------", "test new approach");
}
}
}

相关内容