安卓自学笔记:15:通过XML设置监听器

来源:互联网 发布:山东理工大学知乎 编辑:程序博客网 时间:2024/05/29 16:25

    在xml中通过onClick设置一个事件处理方法,然后需要在Activity中定义该方法。

主代码:

public class MainActivity extends Activity {@Overrideprotected 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>

运行效果:

0 0
原创粉丝点击