2013-07-19 10 views
12

AndroidビューにはCSSクラスセレクタと同等の機能がありますか? R.idのようなものですが、複数のビューで使用できますか?私は、レイアウトツリー内の位置に関係なく、いくつかのグループのビューを隠したいと思っています。AndroidビューのCSSクラスセレクタに相当しますか?

答えて

4

私はあなたが望むアンドロイド:idを探して、あなたのレイアウトのすべてのビューを反復する必要があると思います。 View setVisibility()を使用して可視性を変更することができます。また、android:idの代わりにView setTag()/ getTag()を使用して、処理したいビューをマークすることもできます。例えば、次のコードのレイアウトを横断する汎用的な方法を使用しています。

// 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

あなたはこのようなすべてのビューのために同じタグを設定することができ、その後、あなたはこのような単純な機能とそのタグを持つすべてのビューを取得することができます:

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; 
} 

Shlomi Schwartz answerで説明したとおりです。明らかに、これはcssクラスほど有用ではありません。しかしこれは、あなたのビューを何度も反復するためのコードを書くことと比べて、少し役に立ちます。

関連する問題