复选框值为true,但未显示刻度线-Android / Java

Moh*_*rie 5 java checkbox android android-fragments

基本上,我在三(3)个不同的片段中有三(3)个复选框列表。当我打开活动时,默认片段中的复选框显示为正常,但不同片段中的复选框显示为不同。复选框的值仍然为true。下面是复选框的图像,它使内容和我的代码更加清晰。

第一个片段页面:

在此处输入图片说明

第二个片段页面:

在此处输入图片说明

设置复选框及其代码的代码 if condition

private void setCheckBox(ArrayList<DataPrefType> arrayList){
    for(int i = 0; i < arrayList.size(); i++){
        id = i + 1;
        checkBox = new CheckBox(getActivity());
        checkBox.setId(i + 1);
        checkBox.setText(arrayList.get(i).getName());
        checkBox.setPadding(10, 10, 10, 10);
        checkBox.setLayoutParams(params);
        checkBox.setGravity(Gravity.CENTER);
        checkBoxLayout.addView(checkBox);

        if(!userPreference.isEmpty() || userPreference != null){
            for(int j = 0; j < userPreference.get(0).getDataPrefTypeArrayList().size(); j++){
                int retrieveId = Integer.parseInt(userPreference.get(0).getDataPrefTypeArrayList().get(j).getId());
                if(checkBox.getId() == retrieveId)
                    checkBox.setChecked(true);
            }
        }
Run Code Online (Sandbox Code Playgroud)

Mir*_*ole 9

即使 isChecked 为真,复选框也未显示为已选中的错误存在于绘制动画中。

我在这里找到了这个解决方案。我将其发布在这里作为答案,以便更容易找到并包含一些有关如何调用它的额外信息。

尝试调用jumpDrawablesToCurrentState根视图(或复选框的父视图)。如果专门调用checkBox.setChecked(true);OP 是,请在之后调用它。在这个问题中,在将所有复选框添加到父视图之后调用它是很重要的。这基本上将绘制当前状态下的所有可绘制对象,跳过动画过程。

例子:

@Override
public void onStart() {
    View v = getView();
    if(v != null) {
        CheckBox chkYourCheckBox = (CheckBox)v.findViewById(R.id.chkYourCheckBox);
        chkYourCheckBox.setChecked(true); //sometimes this may draw fine, and other times it may not
        //***The important line:
        v.jumpDrawablesToCurrentState();
    }
}
Run Code Online (Sandbox Code Playgroud)


xSo*_*oDx 1

您可以重写 Fragment 的setUserVisibleHint()方法并在其中的复选框中加载。

@Override
public void setUserVisibleHint(boolean isVisibleToUser) {
        super.setUserVisibleHint(isVisibleToUser);
        if(isVisibleToUser)setCheckBox();
}
Run Code Online (Sandbox Code Playgroud)

这只是一种解决方法,我不认为这是解决该问题的最佳方法,但我还没有找到更好的方法。这可能会导致空指针异常。