react-native-navigation的迁移库

ViewUtils.java 2.6KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283
  1. package com.reactnativenavigation.utils;
  2. import android.support.annotation.Nullable;
  3. import android.view.View;
  4. import android.view.ViewGroup;
  5. import java.util.ArrayList;
  6. import java.util.List;
  7. public class ViewUtils {
  8. @Nullable
  9. public static <T> T findChildByClass(ViewGroup root, Class clazz) {
  10. for (int i = 0; i < root.getChildCount(); i++) {
  11. View view = root.getChildAt(i);
  12. if (clazz.isAssignableFrom(view.getClass())) {
  13. return (T) view;
  14. }
  15. if (view instanceof ViewGroup) {
  16. view = findChildByClass((ViewGroup) view, clazz);
  17. if (view != null && clazz.isAssignableFrom(view.getClass())) {
  18. return (T) view;
  19. }
  20. }
  21. }
  22. return null;
  23. }
  24. public static <T> List<T> findChildrenByClassRecursive(ViewGroup root, Class clazz) {
  25. ArrayList<T> ret = new ArrayList<>();
  26. for (int i = 0; i < root.getChildCount(); i++) {
  27. View view = root.getChildAt(i);
  28. if (view instanceof ViewGroup) {
  29. ret.addAll(findChildrenByClassRecursive((ViewGroup) view, clazz));
  30. }
  31. if (clazz.isAssignableFrom(view.getClass())) {
  32. ret.add((T) view);
  33. }
  34. }
  35. return ret;
  36. }
  37. public static <T> List<T> findChildrenByClass(ViewGroup root, Class clazz) {
  38. return findChildrenByClass(root, clazz, child -> true);
  39. }
  40. public static <T> List<T> findChildrenByClass(ViewGroup root, Class clazz, Matcher<T> matcher) {
  41. List<T> ret = new ArrayList<>();
  42. for (int i = 0; i < root.getChildCount(); i++) {
  43. View child = root.getChildAt(i);
  44. if (clazz.isAssignableFrom(child.getClass()) && matcher.match((T) child)) {
  45. ret.add((T) child);
  46. }
  47. }
  48. return ret;
  49. }
  50. public interface Matcher<T> {
  51. boolean match(T child);
  52. }
  53. public static boolean isChildOf(ViewGroup parent, View child) {
  54. if (parent == child) return true;
  55. for (int i = 0; i < parent.getChildCount(); i++) {
  56. View view = parent.getChildAt(i);
  57. if (view == child) {
  58. return true;
  59. }
  60. if (view instanceof ViewGroup) {
  61. if (isChildOf((ViewGroup) view, child)) return true;
  62. }
  63. }
  64. return false;
  65. }
  66. public static int getPreferredHeight(View view) {
  67. if (view.getLayoutParams() == null) return 0;
  68. return view.getLayoutParams().height < 0 ? view.getHeight() : view.getLayoutParams().height;
  69. }
  70. }