2023年3月8日(软件工程日报)

在Android体系中,CompoundButton类是抽象的,复合按钮,因为是抽象类,所以它不能直接使用。实际开发中用的是CompoundButton的几个派生类,主要有复选框CheckBox、单选按钮RadioButton以及开关按钮Switch,这些派生类均可使用CompoundButton的属性和方法。加之CompoundButton本身继承了Button类
CompoundButton在XML文件中主要使用下面两个属性。
checked:指定按钮的勾选状态,true表示勾选,false则表示未勾选。默认为未勾选。
button:指定左侧勾选图标的图形资源,如果不指定就使用系统的默认图标。
CompoundButton在Java代码中主要使用下列4种方法。
setChecked:设置按钮的勾选状态。
setButtonDrawable:设置左侧勾选图标的图形资源。
setOnCheckedChangeListener:设置勾选状态变化的监听器。
isChecked:判断按钮是否勾选。
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
android:padding="5dp" >
<CheckBox
android:id="@+id/ck_system"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="5dp"
android:checked="false"
android:text="这是系统的CheckBox"
android:textColor="@color/black"
android:textSize="17sp" />
</LinearLayout>
View Code
public class CheckBoxActivity extends AppCompatActivity
implements CompoundButton.OnCheckedChangeListener {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_check_box);
CheckBox ck_system = findViewById(R.id.ck_system);
CheckBox ck_custom = findViewById(R.id.ck_custom);
ck_system.setOnCheckedChangeListener(this);
ck_custom.setOnCheckedChangeListener(this);
}
@Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
String desc = String.format("您%s了这个CheckBox", isChecked ? "勾选" : "取
消勾选");
buttonView.setText(desc);
}
}
View Code
Switch是开关按钮,它像一个高级版本的CheckBox,在选中与取消选中时可展现的界面元素比复选框丰
富。Switch控件新添加的XML属性说明如下:
textOn:设置右侧开启时的文本。
textOff:设置左侧关闭时的文本。
track:设置开关轨道的背景。
thumb:设置开关标识的图标。
<CheckBox
android:id="@+id/ck_status"
android:layout_width="60dp"
android:layout_height="30dp"
android:background="@drawable/switch_selector"
android:button="@null" />

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:state_checked="true" android:drawable="@drawable/switch_on"/>
<item android:drawable="@drawable/switch_off"/>
</selector>
View Code

 

posted @ 2023-03-08 21:28  摆烂达人  阅读(10)  评论(0编辑  收藏  举报