Вопрос

I have set up a search interface for my app. How can I only display the buttons whose text contains the search string based on my search results which are returned as a string?

Это было полезно?

Решение

You can loop through the children of a ViewGroup to search the text:

public static List<View> searchViews(ViewGroup group, String query) {
  ArrayList<View> foundViews = new ArrayList<View>();
  query = query.toLowerCase();

  for (int i = 0; i < group.getChildCount(); i++) {
    View view = group.getChildAt(i);
    String text = null;
    Class c = view.getClass();
    if (view instanceof Button) { // RadioButton is actually a subclass of Button
      Button rb = (Button)view;
      text = (String) rb.getText();
    }
    // ... and maybe check other types of View

    if (text == null) {
      continue;
    }

    text = text.toLowerCase();
    if (text.contains(query)) {
      foundViews.add(view);
    }
  }

  return foundViews;
}
Лицензировано под: CC-BY-SA с атрибуция
Не связан с StackOverflow
scroll top