相当于Android视图的CSS类选择器?

时间:2013-07-19 13:04:27

标签: android view css-selectors

Android视图是否具有与CSS类选择器相同的功能?像R.id这样的东西,但可用于多个视图?我想隐藏一些视图,而不考虑它们在布局树中的位置。

2 个答案:

答案 0 :(得分:4)

我认为你需要遍历布局中的所有视图,寻找你想要的android:id。然后,您可以使用View setVisibility()来更改可见性。您还可以使用View setTag()/ getTag()而不是android:id来标记要处理的视图。例如,以下代码使用通用方法遍历布局:

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

答案 1 :(得分: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类有用。但与编写代码以反复迭代您的视图相比,这可能有点用处。