天天看点

android:onClick属性使用之ToggleButton

关于onClick监听使用

通过函数注册给android:onClick的监听器,个人感觉这种给按钮添加动作比较简单,分享给大家。

在XML中指定按钮的onClick属性,当点击按钮时会根据反射的方式调用Activity中对应的方法。该属性值和要调用的方法名称相同。

在此用了ToggleButton来做,它是一个特殊的Button,同样具有onclick属性,如下代码:

MainActivity.java

publicclass MainActivity extendsActivity {

     //声明

     privateImageView image;

     privateToggleButton tobt;

    @Override

    protectedvoid onCreate(BundlesavedInstanceState) {

        super.onCreate(savedInstanceState);

        setContentView(R.layout.activity_main);

        image=(ImageView) findViewById(R.id.image);    //初始化

        tobt=(ToggleButton) findViewById(R.id.toggleButton1);       

    }

   //点击ToggleButton就会响应onClick()方法

    publicvoid onClick(View v){

       //第一次点击响应的事件

       if(tobt.isChecked()){

            image.setImageResource(R.drawable.on);

       }

       else

           //再次点击响应的事件

            image.setImageResource(R.drawable.off);

    }        

}

Main.xml.XML文件:注意设置onClick属性

<LinearLayout  xmlns:android="http://schemas.android.com/apk/res/android"

    xmlns:tools="http://schemas.android.com/tools"

    android:layout_width="match_parent"

    android:layout_height="match_parent" 

    android:orientation="vertical"

    tools:context="com.example.mbutton.MainActivity">

    <ToggleButton

        android:id="@+id/toggleButton1"

        android:layout_width="match_parent"

        android:layout_height="wrap_content"  

        android:textOn="@string/on"     

        android:textOff="@string/off"    

        android:onClick="onClick"       

        android:text="ToggleButton"/>

    <ImageView

        android:id="@+id/image"

        android:layout_width="fill_parent"

        android:layout_height="match_parent"

        android:background="@drawable/off"/>

</LinearLayout>

效果图:

android:onClick属性使用之ToggleButton
android:onClick属性使用之ToggleButton

继续阅读