Adam Adam - 1 year ago 91
Android Question

Equivalent of CSS class selectors for Android views?

Do Android views have something equivalent to CSS class selectors? Something like but usable for multiple views? I would like to hide some group of views independent of their position in the layout tree.

Answer Source

I think that you will need to iterate through all of the views in your layout, looking for the android:id you want. You can then use View setVisibility() to change the visibility. You could also use the View setTag() / getTag() instead of android:id to mark the views that you want to handle. E.g., the following code uses a general purpose method to traverse the layout:

// Get the top view in the layout.
final View root = getWindow().getDecorView().findViewById(;

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

// Hide any view in the layout whose Id equals
findViewsById(root,, 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) {
    if (v instanceof ViewGroup) {
        final ViewGroup vg = (ViewGroup) v;
        for (int i = 0; i < vg.getChildCount(); i++) {
            findViewsById(vg.getChildAt(i), id, viewHandler);
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download