Android ToggleButton 详解及实例代码

Android ToggleButton 详解

在Android的开发过程中,对于ToggleButton的使用频率也是相当的高的,下面我就来说一下,这个组件的两种使用方式。

第一种是简单的使用,利用Toast的方式弹出提示语句

需要注意的是要想自定义ToggleButton的显示的内容,就需要设置其TextOn和TextOff的内容。

<ToggleButton    android:id="@+id/toggleButton1"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignBaseline="@+id/toggleButton2"    android:layout_alignBottom="@+id/toggleButton2"    android:textOn="开"    android:textOff="关"    android:layout_alignRight="@+id/imageview"    android:text="Simple test" />

然后是主要的显示代码:

case R.id.toggleButton1:      if(SimpleTest.isChecked()){        Toast.makeText(getApplication(), "你打开了开按钮", Toast.LENGTH_SHORT).show();      }else{        Toast.makeText(getApplication(), "你打开了关按钮", Toast.LENGTH_SHORT).show();      }      break;      //应该注意的是,先声明ToggleButton并初始化,然后注册侦听方法

接下来是一个较为复杂一点的使用案例,那就是配合ImageView来实现不同的图片显示状态

<ToggleButton    android:id="@+id/toggleButton2"    android:layout_width="wrap_content"    android:layout_height="wrap_content"    android:layout_alignLeft="@+id/imageview"    android:layout_alignParentTop="true"    android:layout_marginTop="46dp"    android:textOn="美女"    android:textOff="图标"    android:text="With Image" /> <ImageView     android:id="@+id/imageview"    android:layout_width="match_parent"    android:layout_height="wrap_content"    android:src="@drawable/note"    android:layout_below="@id/toggleButton2"    />

然后是活动代码

case R.id.toggleButton2:      if(WithImage.isChecked()){        imageview.setImageResource(R.drawable.note);      }else{        imageview.setImageResource(R.drawable.ic_launcher);      }      break;

需要注意的是,我们同样需要先进行声明,才能对其使用,否则会报空指针的错误。

下面是程序运行之后的结果

总结与设想:

在使用过程中使用到的ToggleButton 一般来说不会这么的简单,但是主要的思想和框架还是基于这里的。我们可以在相关的侦听方法中添加比如静音的处理,或者status的改变等等。这样,我们的应用就会变得更加的灵活了。

想做你的有缘人,可是我知道结果是惨淡的,但还是心存希望!

Android ToggleButton 详解及实例代码

相关文章:

你感兴趣的文章:

标签云: