Android之如何在XML中添加单击事件

来源:互联网 发布:微信红包埋雷必中软件 编辑:程序博客网 时间:2024/06/05 03:57
如何在XML中添加单击事件?


例如给TextVeiw添加单击事件:




  <TextView
        android:id="@+id/tv"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:background="#ffcc00"
        android:clickable="true"//设置可以点击,TextView默认是不能点击的
        android:onClick="showMsg"//设置点击的方法名
        android:text="设置单击事件"
        android:singleLine="true"
        android:tag="hello" />
   
    </TextView>


    在Activity中设置单击方法,方法名要和XML中的一样


    public void showMsg(View view){
//必须写参数,View是事件源,回调的时候传入事件源
Toast.makeText(this, tv.getTag().toString(),Toast.LENGTH_LONG).show();


}
1 0
原创粉丝点击