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

Ada*_*dam 14 android view css-selectors

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

Yoj*_*mbo 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);
        }
    }
}
Run Code Online (Sandbox Code Playgroud)