【问题标题】:CheckBox set checked programmatically without animatingCheckBox 设置以编程方式检查而无需动画
【发布时间】:2016-12-14 23:20:54
【问题描述】:
我有一个 ListView,其中每个项目都是一个 CheckBox。我将每个项目的状态保存在 ArrayList 中,以确保回收的视图不会混淆。
唯一的问题是我必须在每个 CheckBox 行项目上使用 setChecked,它首先显示选中,然后显示取消选中动画。
有没有办法在没有动画的情况下在 CheckBox 上强制 setChecked?瞬间,我的意思是。
【问题讨论】:
标签:
android
listview
arraylist
checkbox
【解决方案1】:
您不需要实现自己的可绘制对象。只需像这样使用方法jumpDrawablesToCurrentState():
private fun setChecked(
btn: CompoundButton,
checked: Boolean,
withTransition: Boolean
) {
btn.isChecked = checked
if (!withTransition) {
btn.jumpDrawablesToCurrentState()
}
}
【解决方案2】:
您可以这样做的一种方法是在CheckBox 中使用您自己的支票图像。您需要不同状态的图像,您可以从 http://android-holo-colors.com/ 获得这些图像
然后我们可以在代码中引用这些可绘制对象:
Drawable mEnabledBg = getResources().getDrawable(R.drawable.check_bg_enabled);
Drawable mCheckedBg = getResources().getDrawable(R.drawable.check_bg_checked);
Drawable mDisabledBg = getResources().getDrawable(R.drawable.check_bg_disabled);
现在,我们在 StateListDrawbles 中使用它们:
StateListDrawable tickColorStates = new StateListDrawable();
tickColorStates.addState(new int[]{android.R.attr.state_checked}, mCheckedBg); //checked
tickColorStates.addState(new int[]{-android.R.attr.state_checked, android.R.attr.state_enabled}, mEnabledBg); //un-checked
tickColorStates.addState(new int[]{-android.R.attr.state_enabled}, mDisabledBg); //disabled
checkBox.setButtonDrawable(tickColorStates);
当然,此设置也可以在 xml 中完成,然后您只需调用 setButtonDrawable()。希望这会有所帮助。