14

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

4

2 に答える 2

4

必要な android: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);
        }
    }
}
于 2013-07-19T14:51:47.590 に答える
4

そのようなすべてのビューに同じタグを設定すると、次のような単純な関数でそのタグを持つすべてのビューを取得できます。

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 クラスほど有用ではありません。しかし、これは、コードを記述してビューを何度も反復することに比べれば、少し便利かもしれません。

于 2014-04-18T10:16:17.590 に答える