安卓动态创建的复选框选项已预先检查?

时间:2015-01-20 05:09:27

标签: android checkbox

我正在创建一个应用程序,其中我需要预先检查动态创建的复选框的特定或多个选项。到目前为止,我已经能够创建并获取动态创建的复选框的id并将其存储在arraylist中。我的问题是如何使用arraylist的值,例如:[1,2]并预先选中复选框的选项1和2

这是我的代码:

   private void addCheckButtons() {

   public static ArrayList<String> selchkboxlist=new ArrayList<String>();
   String chk,isa;

   String options[] = { op1, op2, op3, op4,op5 };

   for (int i = 0; i <totalchoice; i++) {
   checkedTextView=new CheckBox(this);
   checkedTextView.setText("");
   checkedTextView.setId(i);
   checkedTextView.setText(options[i]);
   checkedTextView.setTextColor(Color.BLACK);

   checkedTextView.setOnClickListener( new View.OnClickListener()
     { 
         public void onClick(View v) 
         { 
            CheckBox cb = (CheckBox) v ; 

        if (((CheckBox) v).isChecked()) {
            chk = Integer.toString(v.getId()+1);

                selchkboxlist.add(chk);

        } 
       else if (!((CheckBox) v).isChecked()){
            chk = Integer.toString(v.getId()+1);
             selchkboxlist.remove(chk);
             System.out.println("RemoveCHECK="+selchkboxlist);
            }

        isa=String.valueOf(selchkboxlist);
        String regex = "\\[|\\]";
        isa=isa.replaceAll(regex, "");

        }
 });

   rc.addView(checkedTextView); 
    }   
}}

2 个答案:

答案 0 :(得分:0)

使用setChecked()方法。这样您就可以更改Widget的已检查状态。

[编辑]这是我想出的东西(没有保证,我没有编译或测试它!)

private void addCheckButtons() {

// This must be prepopulated with checked items. Also, is static the right storage class?
public static Set<Integer> selchkboxlist = new Set<Integer>();

String options[] = { op1, op2, op3, op4,op5 };
for (int i = 0; i <totalchoice; i++) {
    checkedTextView=new CheckBox(this);
    checkedTextView.setText("");
    checkedTextView.setId(i);
    checkedTextView.setText(options[i]);
    checkedTextView.setTextColor(Color.BLACK);
    checkedTextView.setChecked(selchkboxlist.contains(i));

    checkedTextView.setOnClickListener( new View.OnClickListener() { 
        public void onClick(View v) { 
            CheckBox cb = (CheckBox) v; 

            if (cb.isChecked()) {
                selchkboxlist.add(i);
            } 
            else{
                selchkboxlist.remove(i);
                System.out.println("RemoveCHECK="+selchkboxlist);
            }
        }
    });

    rc.addView(checkedTextView); 
}   
}}

答案 1 :(得分:0)

试试这个代码它会起作用(我在一个arrayList中维护状态)

ArrayList<MyQuestionBean> mList=new ArrayList<MyQuestionBean>();

在MainActivity.java中

public class MainActivity extends Activity {

protected static final String TAG = "MainActivity";
private LinearLayout mLayout;
private ArrayList<MyQuestionBean> mQuestionsList;
private int current_questionID = 0;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    setContentView(R.layout.activity_main);
    mLayout = (LinearLayout) findViewById(R.id.questionlayoutid);
    mQuestionsList = getQuestionsList();
}

@Override
protected void onResume() {
    super.onResume();
    showCurrentQuestion(current_questionID);
}

private void showCurrentQuestion(final int qustionID) {
    current_questionID = qustionID;
    // for question number
    final MyQuestionBean mMyQuestionBean = mQuestionsList.get(qustionID);
    Log.v(TAG, mMyQuestionBean + "");

    TextView mQuestionNo = new TextView(this);
    mQuestionNo.setText(mMyQuestionBean.getQuestion_id() + "");
    mQuestionNo.setPadding(10, 10, 10, 10);
    mQuestionNo.setTextColor(getResources().getColor(R.color.black));
    // for question
    TextView mQuestion = new TextView(this);
    mQuestion.setText(mMyQuestionBean.getQuestion_name());
    mQuestion.setPadding(10, 10, 10, 10);
    mQuestion.setTextColor(getResources().getColor(R.color.black));
    // adding question and answer
    mLayout.addView(mQuestionNo);
    mLayout.addView(mQuestion);
    // create the check box as per the number of options in
    String[] options_answers = mMyQuestionBean.getOptions_answers();
    ArrayList<CheckBox> mBoxs = new ArrayList<CheckBox>();
    for (int i = 0; i < options_answers.length; i++) {
        CheckBox mCheckBx = new CheckBox(this);
        mCheckBx.setText(options_answers[i]);
        mCheckBx.setId(i);
        mCheckBx.setTextColor(Color.BLACK);
        mLayout.addView(mCheckBx);
        mBoxs.add(mCheckBx);
        mCheckBx.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                if (isChecked) {
                    if (mMyQuestionBean.isAnswered()) {
                        String mQuestion_result = mMyQuestionBean.getQuestion_result();
                        mQuestion_result = mQuestion_result + buttonView.getId();
                        mMyQuestionBean.setQuestion_result(mQuestion_result);
                    } else {
                        mMyQuestionBean.setQuestion_result(buttonView.getId() + "");
                        mMyQuestionBean.setAnswered(true);
                    }
                }
            }
        });

    }

    for (int i = 0; i < mBoxs.size(); i++) {
        CheckBox checkBox = mBoxs.get(i);
        if (mMyQuestionBean.getQuestion_result().contains(i + "")) {
            checkBox.setChecked(true);
        } else {
            checkBox.setChecked(false);
        }
    }

}

public void nextQuestion(View v) {
    int temp = current_questionID + 1;
    if (temp < mQuestionsList.size()) {
        mLayout.removeAllViews();
        showCurrentQuestion(temp);
    }

}

public void previousQuestion(View v) {
    int temp = current_questionID - 1;
    if (temp >= 0) {
        mLayout.removeAllViews();
        showCurrentQuestion(temp);
    }
}

private MyQuestionBean getQuestion(int questionNumber, String questionName, String[] option_answers) {
    // By default isAnswered is false and question_result is empty("")
    MyQuestionBean mBean = new MyQuestionBean();
    mBean.setQuestion_id(questionNumber);
    mBean.setQuestion_name(questionName);
    mBean.setOptions_answers(option_answers);
    mBean.setAnswered(false);
    mBean.setQuestion_result("");
    return mBean;
}

private ArrayList<MyQuestionBean> getQuestionsList() {
    ArrayList<MyQuestionBean> myQuestionBeans = new ArrayList<MyQuestionBean>();
    MyQuestionBean question1 = getQuestion(1, "what is your favorite color", new String[] { "red", "green", "blue" });
    MyQuestionBean question2 = getQuestion(2, "what is your favorite hero", new String[] { "ram", "ajith", "komal", "chandu" });
    MyQuestionBean question3 = getQuestion(3, "what is your favorite place", new String[] { "hyd", "banguluru" });
    myQuestionBeans.add(question1);
    myQuestionBeans.add(question2);
    myQuestionBeans.add(question3);
    return myQuestionBeans;
}
}

在MyQuestionBean.java中

public class MyQuestionBean {
private String question_name;
private int question_id;
private String[] options_answers;
private boolean isAnswered;
private String question_result;

public String[] getOptions_answers() {
    return options_answers;
}

public void setOptions_answers(String[] options_answers) {
    this.options_answers = options_answers;
}

public int getQuestion_id() {
    return question_id;
}

public void setQuestion_id(int question_id) {
    this.question_id = question_id;
}

public boolean isAnswered() {
    return isAnswered;
}

public void setAnswered(boolean isAnswered) {
    this.isAnswered = isAnswered;
}

public String getQuestion_result() {
    return question_result;
}

public void setQuestion_result(String question_result) {
    this.question_result = question_result;
}

public String getQuestion_name() {
    return question_name;
}

public void setQuestion_name(String question_name) {
    this.question_name = question_name;
}

public MyQuestionBean() {
    super();
}

}

在activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/main_activity"
android:layout_width="match_parent"
android:layout_height="match_parent" >

<LinearLayout
    android:id="@+id/questionlayoutid"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    android:orientation="vertical"
    android:paddingTop="10dp" >
</LinearLayout>

<Button
    android:id="@+id/nextbttnid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:onClick="nextQuestion"
    android:layout_alignParentRight="true"
    android:text="nextbttn" />

<Button
    android:id="@+id/previousbttnid"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_alignParentBottom="true"
    android:layout_alignParentLeft="true"
    android:onClick="previousQuestion"
    android:text="prevbttn" />

</RelativeLayout>