我正在玩我的第一个 Android 应用程序 - 这是一个简单的计算器,可以根据商品的最终销售价格和任何其他附加费用计算出商品的总成本。其中一项费用是税费,它并不总是适用于所有项目,因此我添加了一个复选框来指定在计算成本时是否适用增值税。
我在java中创建了一个方法来切换复选框的选中状态并将其绑定(bind)到复选框的onClick事件,但是当我按下复选框时没有任何反应。
这是java代码:
public void changeCheckedState(View view) {
CheckBox checkBox = (CheckBox)findViewById(R.id.cbIncludeVAT);
checkBox.setChecked(!checkBox.isSelected());
}
这是复选框 View 的 xml:
<CheckBox
android:id="@+id/cbIncludeVAT"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="8dp"
android:layout_marginTop="26dp"
android:checked="true"
android:onClick="changeCheckedState"
android:text="Include VAT?"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintTop_toBottomOf="@+id/lblCardFee" />
我正在 Android 手机上运行/测试该应用程序,但无法进行调试,因此我不知道当我按下复选框时事件处理程序是否会触发。
我已经搜索了解决方案并尝试了各种修复,但似乎没有任何效果 - 复选框只是保持选中状态(它是默认/启动状态)。
最佳答案
he check box simply remains checked (it's default/starting state).
当您点击 checkbox
checkBox.isSelected()
时,您会得到 true
并且 !
会将其翻转为false
因此 checkbox
将始终设置为 false
表示未选中。
checkBox.isSelected() // true when your click
checkBox.setChecked(!checkBox.isSelected()); // ! will convert it to false
// so checkbox will always be set to unchecked by this code
注意:您不需要设置复选框
状态
public void changeCheckedState(View view) {
CheckBox checkBox = (CheckBox)findViewById(R.id.cbIncludeVAT);
// ^^^^ declare it outside
// initialize checkBox inside oncreate rather than doing on every click
if(checkBox.isSelected()){
// box is checked
}else{
// box is unchecked
}
}
关于java - 单击时切换复选框的选中状态,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/44594308/