preview
ToggleButton有两种状态:选中和未选中状态,并且需要为不同的状态设置不同的显示文本
ToggleButton属性:android:checked=”true”
android:textOn=”开”——-按钮被点击时显示的文字内容
android:textOff=”关”——-按钮未被点击时显示的文字内容
exercise
实现一个东西:点击ToggleButton时ImageView的背景会改变
在layout下先加入控件
<!--当true的时候显示textOn,false的时候显示textOff。
如果不声明android:checked="true"的话,默认情况为android:checked="false"-->
<ToggleButton
android:text="ToggleButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:textOn="开"
android:textOff="关"
android:id="@+id/toggleButton" />
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@mipmap/off"
android:id="@+id/imageView" />
在Activity下
public class MainActivity extends AppCompatActivity {
private ToggleButton togBut;
private ImageView image;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
togBut=(ToggleButton) findViewById(R.id.toggleButton);
image=(ImageView) findViewById(R.id.imageView);
//设置监听器
togBut.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
@Override
//compoundButton---代表被点击控件本身;b---代表被点击的控件的状态
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
//当togBut被点击时,当前方法执行。括号内意思是如果b为true时imageView的背景用名字为on的图片,false用名字为off的图片
image.setBackgroundResource(b?R.mipmap.on:R.mipmap.off);
}
});
}
}