Android视图的CSS类选择器等效物是什么?

15
Android视图是否有类似于CSS类选择器的东西?是否有像 R.id 一样可用于多个视图的选项?我想隐藏某些视图组,而不考虑它们在布局结构中的位置。
2个回答

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

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 答案所解释的那样。显然,这与CSS类不如有用。但是与再次迭代视图的编写代码相比,这可能会有点有用。

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接