2017-10-07 50 views
1

我已經創建了動態視圖。該視圖包含兩個edittext和一個廣播組。當我點擊添加按鈕時,視圖被添加到佈局。現在我感到困惑,如何從這些類型的動態視圖中獲取值。我試過了,但它不起作用。當我添加兩個或多個視圖時,循環沒有找到下一個視圖值。我想將該值添加到ArrayList。這是代碼:如何從動態編輯文本和廣播組中獲取值?

私人無效addDynamicViews(){

EditText name = new EditText(this); 
EditText mobile = new EditText(this); 

LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT); 
p.setMargins(10, 10, 5, 5); 

name.setLayoutParams(p); 
name.setBackgroundResource(R.drawable.edittext_box); 
name.setHint("Enter Name"); 
studentslayout.addView(name); 

mobile.setLayoutParams(p); 
mobile.setBackgroundResource(R.drawable.edittext_box); 
mobile.setHint("Enter Mobile No"); 
studentslayout.addView(mobile); 

/* radioGroup - Radio Group 
maleButton,femaleButton - Radio Buttons 
studentslayout - Linear Layout */ 

radioGroup = new RadioGroup(this); 
radioGroup.setOrientation(RadioGroup.VERTICAL); 
maleButton = new RadioButton(this); 
maleButton.setText("Male"); 
radioGroup.addView(maleButton); 

femaleButton = new RadioButton(this); 
radioGroup.addView(femaleButton); 
femaleButton.setText("Female"); 
studentslayout.addView(radioGroup); 
} 

如何採取一切動態的EditText和無線電集團的價值觀? 我試過這段代碼但不幸的是它停了。

@Override 
      public void onClick(View v) { 

       String[] array = new String[studentslayout.getChildCount()]; 
       int count = studentslayout.getChildCount(); 
       for (int i=0; i < studentslayout.getChildCount(); i++){ 

        editText = (EditText)studentslayout.getChildAt(i); 
        array[i] = editText.getText().toString(); 

        RadioButton radValues = (RadioButton) studentslayout.getChildAt(i); 
        array[i] = radValues.getText().toString(); 

       } 
      } 
+0

對不起不工作 – suryac

+0

如何獲得兼具動感的EditText和無線電集團的價值觀?請幫助我 – suryac

回答

1
RadioButton radValues = (RadioButton) studentslayout.getChildAt(i); 

您已經添加radioGroup中,並期待單選按鈕。此外,由於您正在循環,您應該檢查視圖的類型。

你可以嘗試這樣的事情:

int childCount = studentslayout.getChildCount(); 
for (int i = 0; i < childCount; i++) { 
    View childView = studentslayout.getChildAt(i); 
    if (childView instanceof EditText) { 
     EditText editText = (EditText) childView; 
     String text = editText.getText().toString(); 
     //use text 
    } else if (childView instanceof RadioGroup) { 
     RadioGroup radioGroup = (RadioGroup) childView; 
     int radioCount = radioGroup.getChildCount(); 
     for (int j = 0; j < radioCount; j++) { 
      RadioButton radioButton = (RadioButton) radioGroup.getChildAt(i); 
      //use radioButton. 
     } 
    } 
} 
+0

感謝您的幫助 – suryac

+0

很高興我可以幫助:) –