CheckedTextView在以编程方式选择时不绘制复选标记

时间:2017-01-24 15:01:48

标签: android listview android-fragments checkedtextview

我正在编写一个Android应用程序,其中包含带有CheckedTextView项目的ListView。它基本上是一个答案数量可变的问题。如果您选择一个答案,您可以按" next"并看到下一个问题。

我已经编写了所有代码来保存答案并转到下一个问题,而且我还为用户提供了一个"之前的"按钮返回上一个问题。如果上一个问题已经有答案,我希望选择该答案。这就是问题出现的地方。

现在,我可以获取所选答案的位置,然后拨打listView.setItemChecked(pos, true),但未选中单选按钮。

if(selectedAnswer != null) {
    int pos = mAnswerAdapter.getPosition(selectedAnswer);
    if(pos != -1) {
        listAnswers.setItemChecked(pos, true);
    }
}

只有在我执行其他操作时,例如向下拖动状态栏,视图才会刷新并绘制无线电按钮的选定状态。

我在列表中填写如下答案:

mAnswerAdapter = new AnswerArrayAdapter(getContext(), R.layout.listitem_answer, currentQuestion.getAnswers(), user.getLanguage());
listAnswers.setAdapter(mAnswerAdapter);
mAnswerAdapter.notifyDataSetChanged();

供参考:

list_item布局:

<?xml version="1.0" encoding="utf-8"?>
<CheckedTextView xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:minHeight="?attr/listPreferredItemHeightSmall"
    android:drawableStart="@drawable/questionnaire_answer_radio"
    android:drawablePadding="10dp"
    android:gravity="center_vertical"
    android:paddingStart="5dp"
    android:paddingEnd="5dp"
    android:textColor="@android:color/white"
    android:id="@+id/questionnaire_answer_checkbox"/>

适配器:

package be.iminds.mresist;

import android.content.Context;
import android.support.annotation.NonNull;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;

import java.util.List;

import be.iminds.mresist.models.QuestionnaireDefinition;
import butterknife.BindView;
import butterknife.ButterKnife;

public class AnswerArrayAdapter extends ArrayAdapter<QuestionnaireDefinition.Answer> {

    private String mLang;
    private Context mContext;

    public AnswerArrayAdapter(Context context, int textViewResourceId, List<QuestionnaireDefinition.Answer> answers, final String lang) {
        super(context, textViewResourceId, answers);
        this.mContext = context;
        this.mLang = lang;
    }

    @NonNull
    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

        AnswerArrayAdapter.ViewHolder holder = null;
        QuestionnaireDefinition.Answer item = getItem(position);

        if (convertView == null) {
            convertView = inflater.inflate(R.layout.listitem_answer, parent, false);
            holder = new AnswerArrayAdapter.ViewHolder(convertView);
            convertView.setTag(holder);
        } else
            holder = (AnswerArrayAdapter.ViewHolder) convertView.getTag();

        holder.answerText.setText(item.getAnswer(mLang));

        return convertView;
    }


    static class ViewHolder {
        @BindView(R.id.questionnaire_answer_checkbox) CheckedTextView answerText;

        public ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}

相关的片段代码(第一次调用openQuestion发生在onStart上):

/**
     * Opens the question with the corresponding index
     * @param questionIdx
     */
    private void openQuestion(int questionIdx)
    {
        currentQuestionIdx = questionIdx;
        final Question currentQuestion = getCurrentQuestion();

        txtQuestionTitleCounter.setText(String.format(getString(R.string.questionnaire_counter), questionIdx + 1, qAssignment.getDefinition().getQuestions().size()));
        txtQuestion.setText(currentQuestion.getQuestion(user.getLanguage()));
        mAnswerAdapter = new AnswerArrayAdapter(getContext(), R.layout.listitem_answer, currentQuestion.getAnswers(), user.getLanguage());
        listAnswers.setAdapter(mAnswerAdapter);
        mAnswerAdapter.notifyDataSetChanged();


        //If it's not the last question and there are more questions than one, make the next button visible
        if(!isLastQuestion(currentQuestionIdx) && qAssignment.getDefinition().getQuestions().size() > 1)
            mNextButton.setVisibility(View.VISIBLE);
        else
            mNextButton.setVisibility(View.GONE);

        //If it's not the first question and there are more questions than one, make the previous button visible
        if(!isFirstQuestion(currentQuestionIdx) && qAssignment.getDefinition().getQuestions().size() > 1)
            mPreviousButton.setVisibility(View.VISIBLE);
        else
            mPreviousButton.setVisibility(View.GONE);

        //If the question's already been answered, fill in the answer
        markPreviousAnswer(currentQuestion);

    }


/**
     * Marks a previously selected answer
     * @param currentQuestion
     */
    private void markPreviousAnswer(Question currentQuestion) {
        if(qAssignment.getAnswerValues() != null && qAssignment.getAnswerValues().containsKey(currentQuestion.getQuestionKey())) {

            //Value of answer
            Integer value = qAssignment.getAnswerValues().get(currentQuestion.getQuestionKey());
            QuestionnaireDefinition.Answer selectedAnswer = null;
            for(QuestionnaireDefinition.Answer answer: currentQuestion.getAnswers()) {
                if(answer.getValue() == value) {
                    selectedAnswer = answer;
                    break;
                }
            }
            if(selectedAnswer != null) {
                int pos = mAnswerAdapter.getPosition(selectedAnswer);
                if(pos != -1) {
                    listAnswers.setItemChecked(pos, true);
                }
            }
        }
    }

CheckedTextView选择器drawable:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:state_pressed="true">
        <shape android:shape="oval">
            <size android:width="16dp" android:height="16dp"/>
            <solid android:color="@color/colorPrimaryDarker"/>
            <stroke android:color="@android:color/white" android:width="2dp"/>
        </shape>
    </item><!-- pressed -->

    <item android:state_checked="true">
        <shape android:shape="oval">
            <size android:width="16dp" android:height="16dp"/>
            <solid android:color="@color/colorPrimaryDarker"/>
            <stroke android:color="@android:color/white" android:width="2dp"/>
        </shape>
    </item> <!-- checked -->

    <item>
        <shape android:shape="oval" android:innerRadius="10dp">
            <size android:width="16dp" android:height="16dp"/>
            <stroke android:color="@android:color/white" android:width="1dp"/>
        </shape>
    </item> <!-- default -->

</selector>

4 个答案:

答案 0 :(得分:3)

我认为您应该在将答案设置为true后致电notifyDataSetChanged(),以便ListView可以立即刷新其观点

int pos = mAnswerAdapter.getPosition(selectedAnswer);
if(pos != -1) {
    listAnswers.setItemChecked(pos, true);
    mAnswerAdapter.notifyDataSetChanged()
}

答案 1 :(得分:2)

对于简单的复选框,将使用属性按钮:

android:button="@drawable/questionnaire_answer_radio"

对于CheckedTextView,使用checkMark属性:

android:checkMark="@drawable/questionnaire_answer_radio"

答案 2 :(得分:0)

在使用单选按钮等功能时,我遇到了类似的界面问题。将布尔值传递给getView,然后传入getView状态:

boolean checked; //The variable being passed
.
.
.

if(item.getBoolean){   
 radioButton.setChecked(true);
}
else
{
radioButton.setChecked(false);
}

然后当任何人点击更改按钮时,在radioButton的onClick函数中实现以下内容:

if(item.getBoolean){   
 item.setBoolean(false)
 mAnswerAdapter.notifyDatasetChanged();
}
else
{
item.setBoolean(true)
 mAnswerAdapter.notifyDatasetChanged();
}

我希望这会有所帮助

答案 3 :(得分:0)

我无法记住,因为我暂时没有使用ListView列表。如果你使用RecyclerView,你将它与onBindViewHolder绑定到适配器,ListView的等效方法应该可以解决问题。但RecyclerView对于Listview来说是superior

Creata字段,例如,在Adapter类中命名为selectedPosition。当您调用notifyDatasetChanged时,将调用RecyclerView.Adapter的onBindView方法。使用适配器的selectedPosition字段检查要选择的位置,并根据需要更改该位置的视图。

public void onBindViewHolder(MyViewHolder holder, final int position) {
    holder.tvCamMenu.setText(data.get(position));
    if (selectedPosition == position) {
        holder.tvCamMenu.setTextColor(Color.YELLOW);
    } else {
        holder.tvCamMenu.setTextColor(Color.WHITE);
    }
}

这是我用来在水平RecyclerView中设置所选列的颜色的片段。最后调用notifyDatasetChanged,视图将在您选择时将其修改为更改。