2013-03-13 2 views
1

내 조각의 모든 스피너를 포커스로 만들려면 어떻게해야합니까?Android Fragments : 조각 컨트롤을 반복하는 방법

내 레이아웃의 XML에 android:focusableInTouchModeandroid:focusable을 설정해도 아무런 효과가 없습니다.

더 일반적으로 내 Fragment의 컨트롤을 반복하면서 모든 Spinners 또는 모든 EditText와 같은 특정 유형의 컨트롤을 찾는 데 문제가 있습니다.

답변

3

이것은 나에게 매우 까다로운 일 이었기 때문에 여기에 해결책을 게시 할 것이라고 생각했습니다. 이것은 특정 문제를 해결 (포커스 스피너를 만드는 방법)뿐만 아니라보다 일반적인 문제를 해결 (어떻게 조각에서 컨트롤을 통해 루프.

public class MyFragment extends Fragment { 

    private static ArrayList<Spinner> spinners = new ArrayList<Spinner>(); 


    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 

     // inflate the layout 
     View layout = inflater.inflate(R.layout.my_fragment_xml, container, false); 

     // cast our newly inflated layout to a ViewGroup so we can 
     // enable looping through its children 
     set_spinners((ViewGroup)layout); 

     // now we can make them focusable 
     make_spinners_focusable(); 

     return layout; 
    } 

    //find all spinners and add them to our static array 

    private void set_spinners(ViewGroup container) { 
     int count = container.getChildCount(); 
     for (int i = 0; i < count; i++) { 
      View v = container.getChildAt(i); 
      if (v instanceof Spinner) { 
       spinners.add((Spinner) v); 
      } else if (v instanceof ViewGroup) { 
       //recurse through children 
       set_spinners((ViewGroup) v); 
      } 
     } 
    } 

    //make all spinners in this fragment focusable 
    //we are forced to do this in code 

    private void make_spinners_focusable() {    
     for (Spinner s : spinners) { 
      s.setFocusable(true); 
      s.setFocusableInTouchMode(true); 
      s.setOnFocusChangeListener(new View.OnFocusChangeListener() { 
       @Override 
       public void onFocusChange(View v, boolean hasFocus) { 
        if (hasFocus) { 
         v.performClick(); 
        } 
       } 
      }); 
     } 
    } 


} 
1

에서 레이아웃이 중첩 된 경우 set_spinners()으로 선택된 답변이 작동하지 않습니다 getChildCount()은 첫 번째 수준의 하위 항목 만 제공합니다. getAllChildrenBFS을 사용하는 것이 더 좋습니다. answer :

관련 문제