2012-10-15 6 views
0

이 문제와 관련된 다른 질문을 보았지만 솔루션이 제대로 작동하지 않습니다. 페이지에 여러 개의 edittext 필드가 있으며 버튼 하나만 눌러 재설정 할 수 있기를 원합니다. this thread에서 솔루션을 구현했지만 선형 레이아웃을 중첩 시켰으며 주 컨테이너의 직접 자식 인 edittext 만 지 웁니다. edittext 필드를 모두 찾으려면 어떻게해야합니까? 아니면 각 필드를 참조해야합니까?지우기 단추를 사용하여 여러 EditText 필드 지우기

<ScrollView> 
    <LinearLayout android:id="@+id/MainParent"> 
     <LinearLayout> 
      TextView 
      EditText 
     </LinearLayout> 
     <LinearLayout> 
      TextView 
      EditText 
     </LinearLayout> 
     <LinearLayout> 
      TextView 
      EditText 
     </LinearLayout> 
     EditText 
     <LinearLayout> 
      Button1 
      Button2 
     </LinearLayout> 
    </LinearLayout> 
</ScrollView> 

발췌문 자바 파일에서 : 다음과 같이

내 xml 파일 구조는

ViewGroup group = (ViewGroup)findViewById(R.id.MainParent); 
     for (int i = 0, count = group.getChildCount(); i < count; ++i) { 
      View view = group.getChildAt(i); 
       if (view instanceof EditText) { 
        ((EditText)view).setText(""); 
     } 

답변

4

각 E를 참조하는 데 관심이 없다면 ditText 구체적으로, 나는 계층 구조를 처리하는 재귀 함수를 만들 것입니다.

public void clearAll(ViewGroup root) { 
    for (int i = 0, j = root.getChildCount(); i < j, i++) { 
     View view = root.getChildAt(i); 
     if (view instanceof ViewGroup) { 
      clearAll((ViewGroup) view); 
      continue; 
     } 
     if (view instanceof EditText) { 
      ((EditText) view).setText(""); 
      continue; 
     } 
    } 
} 

은 그럼 그냥 전화 :

clearAll((ViewGroup) findViewById(R.id.MainParent)); 
+0

감사합니다. – adohertyd

1

조치의 onclick을 단계 아래 수행 후 :

EditText firstEditText = (EditText) findViewById(R.id.yoursXmlId); 
firstEditText.setText(""); 
+0

그래도 각 글고 필드에이 코드를 반복해야합니다. 이 일을 피할 수있는 방법이 있습니까? – adohertyd

+0

onCreate() 메서드에서 editText를 한 번만 선언해야하고 모든 편집 텍스트에서 빈 텍스트를 설정하여 함수를 호출하고 필요할 때마다 함수를 호출해야합니다. –

+0

아 고맙습니다. – adohertyd

1
LinearLayout group = (LinearLayout)findViewById(R.id.MainParent); 
     for (int i = 0, count = group.getChildCount(); i < count; ++i) 
     { 
      View view = group.getChildAt(i); 
       if (view instanceof EditText) { 
        ((EditText)view).setText(""); 
     } 
+0

Chirag Raval의 답변에 대한 비슷한 제안을 아래에서 볼 수 있습니다. – adohertyd

+0

감사합니다. 여전히 작동하지 않습니다. MainParent의 직계 하위 인 edittext 만 지울 수 있습니다. – adohertyd

관련 문제