2014-10-27 28 views
0

我有一個XML,其中TextViewCheckBox,現在我將它們添加到一個活動, 我添加多少取決於有多少問題,但如果複選框被選中我想查看哪一個,我該怎麼做?如何查看當動態添加它們時檢查哪個複選框

for (int i = 0; i< questions.size(); i++) { 

    View view1 = View.inflate(Checklist.this, R.layout.question, null); 
    TextView myText = (TextView) view1.findViewById(R.id.questiontext); 
    checkbox = (CheckBox) view1.findViewById(R.id.checkBox); 
    layout.addView(view1); 
    myText.setText(questions.get(i).question); 

    checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      //check which checbox is checked 
     } 
    }); 

} 

這是如何將它們添加到我的視圖。

回答

0

您可以使用setTag設置標籤上的複選框:

在創建:

for (int i = 0; i< questions.size(); i++) { 

    View view1 = View.inflate(Checklist.this, R.layout.question, null); 
    TextView myText = (TextView) view1.findViewById(R.id.questiontext); 
    checkbox = (CheckBox) view1.findViewById(R.id.checkBox); 
    checkbox.setTag(String.valueOf(i)); 
    layout.addView(view1); 
    myText.setText(questions.get(i).question); 

    checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() { 
     @Override 
     public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) { 
      //check which checbox is checked 
      String tag= (String)buttonView.getTag(); 
     } 
    }); 
} 

這將使你的標籤(我),這將指示題號。

希望它有幫助。

+0

不工作,他們得到所有相同的標籤,如果有例如標籤在每個複選框上的3個問題:2 – Rikkert09 2014-10-27 08:06:04

+1

哦,'setTag()'工作,如果我這樣定義複選框: 'final CheckBox checkbox =(CheckBox)view1.findViewById(R.id.checkBox);' 所以謝謝! – Rikkert09 2014-10-27 08:14:56

+0

Try String tag =(String)buttonView.getTag(); v.getTag()中v是什麼? – greenapps 2014-10-27 08:24:09

相關問題