2015-01-20 7 views
0

Я создаю приложение, в котором мне нужно предварительно проверить определенные или несколько вариантов динамически созданных флажков. До сих пор я могу создать и получить идентификаторы динамически созданных флажков и сохранить их в arraylist. Мои вопросы, как использовать значение ArrayList, например: [1,2] и prechecked варианты 1 и 2 флажокAndroid-динамически созданный флажок предварительно установлен?

Вот мой код:

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); 
    } 
}} 
+0

объяснения подробно ?? – KomalG

+0

Я хочу проверить конкретную опцию флажка, который я ранее делал – Aparana

+0

. Я делаю приложение для викторины, в котором есть следующая и предыдущая кнопка, и на кнопке prev, которую я хочу уже проверить, которые были выбраны мной. – Aparana

ответ

0

Используйте метод setChecked(). Это позволяет вам изменить состояние вашего Widget.

[Edit] Вот то, что я придумал (без каких-либо гарантий, я не компилировать или тест тест он!)

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); 
} 
}} 
+0

Я уже использовал метод setchecked(), но он проверял все флажки, но я хочу проверить только значение уже принятых флажков. Пожалуйста, помогите мне. – Aparana

+0

В вашем коде есть множество вещей, которые необычны и излишне сложны. Однако простой ответ состоит в том, чтобы иметь только вызов setChecked() if (checkedTextView.contains (chk). Вызовите это вместе с другим кодом инициализации checkedTextView(), а не в обработчике кликов. – dhaag23

+0

вы можете помочь мне с обновлением в моем коде «Мне нужно начинать, так что помогите мне, если вы сможете. – Aparana

0

попробуйте этот код будет работать (я сохранил состояние в одном Список_массивах)

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> 
Смежные вопросы