2013-07-19 21 views

Trả lời

4

Tôi nghĩ rằng bạn sẽ cần phải lặp qua tất cả các chế độ xem trong bố cục của bạn, tìm kiếm android: id mà bạn muốn. Sau đó, bạn có thể sử dụng View setVisibility() để thay đổi chế độ hiển thị. Bạn cũng có thể sử dụng View setTag()/getTag() thay cho android: id để đánh dấu các khung nhìn mà bạn muốn xử lý. Ví dụ, đoạn mã sau sử dụng một phương pháp mục đích chung để đi qua cách bố trí:

// Get the top view in the layout. 
final View root = getWindow().getDecorView().findViewById(android.R.id.content); 

// Create a "view handler" that will hide a given view. 
final ViewHandler setViewGone = new ViewHandler() { 
    public void process(View v) { 
     // Log.d("ViewHandler.process", v.getClass().toString()); 
     v.setVisibility(View.GONE); 
    } 
}; 

// Hide any view in the layout whose Id equals R.id.textView1. 
findViewsById(root, R.id.textView1, setViewGone); 


/** 
* Simple "view handler" interface that we can pass into a Java method. 
*/ 
public interface ViewHandler { 
    public void process(View v); 
} 

/** 
* Recursively descends the layout hierarchy starting at the specified view. The viewHandler's 
* process() method is invoked on any view that matches the specified Id. 
*/ 
public static void findViewsById(View v, int id, ViewHandler viewHandler) { 
    if (v.getId() == id) { 
     viewHandler.process(v); 
    } 
    if (v instanceof ViewGroup) { 
     final ViewGroup vg = (ViewGroup) v; 
     for (int i = 0; i < vg.getChildCount(); i++) { 
      findViewsById(vg.getChildAt(i), id, viewHandler); 
     } 
    } 
} 
3

Bạn có thể đặt cùng một thẻ cho tất cả các quan điểm như vậy và sau đó bạn có thể nhận được tất cả các quan điểm có tag rằng với một chức năng đơn giản như thế này:

private static ArrayList<View> getViewsByTag(ViewGroup root, String tag){ 
    ArrayList<View> views = new ArrayList<View>(); 
    final int childCount = root.getChildCount(); 
    for (int i = 0; i < childCount; i++) { 
     final View child = root.getChildAt(i); 
     if (child instanceof ViewGroup) { 
      views.addAll(getViewsByTag((ViewGroup) child, tag)); 
     } 

     final Object tagObj = child.getTag(); 
     if (tagObj != null && tagObj.equals(tag)) { 
      views.add(child); 
     } 

    } 
    return views; 
} 

Như được giải thích trong Shlomi Schwartz answer. Rõ ràng điều này không hữu ích như các lớp css. Nhưng điều này có thể hữu ích một chút so với viết mã để lặp lại quan điểm của bạn một lần nữa và một lần nữa.

Các vấn đề liên quan