下面列出了android.view.View#getClass ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* get descended views from parent.
*
* @param parent
* @param filter Type of views which will be returned.
* @param includeSubClass Whether returned list will include views which are subclass of filter or not.
* @return
*/
public static <T extends View> List<T> getDescendants(ViewGroup parent, Class<T> filter, boolean includeSubClass) {
List<T> descendedViewList = new ArrayList<T>();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
Class<? extends View> childsClass = child.getClass();
if ((includeSubClass && filter.isAssignableFrom(childsClass))
|| (!includeSubClass && childsClass == filter)) {
descendedViewList.add(filter.cast(child));
}
if (child instanceof ViewGroup) {
descendedViewList.addAll(getDescendants((ViewGroup)child, filter, includeSubClass));
}
}
return descendedViewList;
}
/**
* get descended views from parent.
*
* @param parent
* @param filter Type of views which will be returned.
* @param includeSubClass Whether returned list will include views which are subclass of
* filter or not.
* @return
*/
public static <T extends View> List<T> getDescendants(ViewGroup parent,
Class<T> filter, boolean includeSubClass) {
List<T> descendedViewList = new ArrayList<T>();
int childCount = parent.getChildCount();
for (int i = 0; i < childCount; i++) {
View child = parent.getChildAt(i);
Class<? extends View> childsClass = child.getClass();
if ((includeSubClass && filter.isAssignableFrom(childsClass))
|| (!includeSubClass && childsClass == filter)) {
descendedViewList.add(filter.cast(child));
}
if (child instanceof ViewGroup) {
descendedViewList.addAll(getDescendants((ViewGroup) child,
filter, includeSubClass));
}
}
return descendedViewList;
}
public static void recycleView(View v) {
Class type = v.getClass();
if (v != null && type != null) {
LinkedList<View> recycleQueue = recycleMap.get(type);
LinkedList<View> usingList = usingMap.get(type);
if (recycleQueue == null) {
recycleQueue = new LinkedList<>();
recycleMap.put(type, recycleQueue);
}
if (usingList == null) {
usingList = new LinkedList<>();
usingMap.put(type, usingList);
}
int index = usingList.indexOf(v);
if (index != -1) {
Object o = v.getTag(TAG_VIEW_CANNOT_RECYCLE);
if (o == null) {
recycleQueue.add(v);
usingList.remove(v);
}
}
}
}
public static View getClickView(String tabHostTag) {
int i = 0;
if (TextUtils.isEmpty(tabHostTag)) {
return null;
}
WindowHelper.init();
View[] windows = WindowHelper.getWindowViews();
try {
View window;
View tabHostView;
while (i < windows.length) {
window = windows[i];
if (window.getClass() != sPopupWindowClazz) {
if ((tabHostView = findTabView(window, tabHostTag)) != null) {
return tabHostView;
}
}
i++;
}
return null;
} catch (Exception e) {
return null;
}
}
/**
* Returns an {@code ArrayList} of {@code View}s of the specified {@code Class} located under the specified {@code parent}.
*
* @param classToFilterBy return all instances of this class, e.g. {@code Button.class} or {@code GridView.class}
* @param includeSubclasses include instances of subclasses in {@code ArrayList} that will be returned
* @param parent the parent {@code View} for where to start the traversal
* @return an {@code ArrayList} of {@code View}s of the specified {@code Class} located under the specified {@code parent}
*/
public <T extends View> ArrayList<T> getCurrentViews(Class<T> classToFilterBy, boolean includeSubclasses, View parent) {
ArrayList<T> filteredViews = new ArrayList<T>();
List<View> allViews = getViews(parent, true);
for(View view : allViews){
if (view == null) {
continue;
}
Class<? extends View> classOfView = view.getClass();
if (includeSubclasses && classToFilterBy.isAssignableFrom(classOfView) || !includeSubclasses && classToFilterBy == classOfView) {
filteredViews.add(classToFilterBy.cast(view));
}
}
allViews = null;
return filteredViews;
}
public static void setSearchViewContentColor(View searchView, final @ColorInt int color) {
if (searchView == null) {
return;
}
final Class<?> cls = searchView.getClass();
try {
final Field mSearchSrcTextViewField = cls.getDeclaredField("mSearchSrcTextView");
mSearchSrcTextViewField.setAccessible(true);
final EditText mSearchSrcTextView = (EditText) mSearchSrcTextViewField.get(searchView);
mSearchSrcTextView.setTextColor(color);
mSearchSrcTextView.setHintTextColor(ColorUtil.adjustAlpha(color, 0.5f));
TintHelper.setCursorTint(mSearchSrcTextView, color);
Field field = cls.getDeclaredField("mSearchButton");
tintImageView(searchView, field, color);
field = cls.getDeclaredField("mGoButton");
tintImageView(searchView, field, color);
field = cls.getDeclaredField("mCloseButton");
tintImageView(searchView, field, color);
field = cls.getDeclaredField("mVoiceButton");
tintImageView(searchView, field, color);
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* Tint the edge effect when you reach the end of a scroll view. API 21+ only
*
* @param scrollableView the scrollable view, such as a {@link android.widget.ScrollView}
* @param color the color
* @return true if it worked, false if it did not
*/
@TargetApi(21)
public static boolean tintEdgeEffect(@NonNull View scrollableView, @ColorInt int color) {
//http://stackoverflow.com/questions/27104521/android-lollipop-scrollview-edge-effect-color
boolean outcome = false;
final String[] edgeGlows = {"mEdgeGlowTop", "mEdgeGlowBottom", "mEdgeGlowLeft", "mEdgeGlowRight"};
for (String edgeGlow : edgeGlows) {
Class<?> clazz = scrollableView.getClass();
while (clazz != null) {
try {
final Field edgeGlowField = clazz.getDeclaredField(edgeGlow);
edgeGlowField.setAccessible(true);
final EdgeEffect edgeEffect = (EdgeEffect) edgeGlowField.get(scrollableView);
edgeEffect.setColor(color);
outcome = true;
break;
} catch (Exception e) {
clazz = clazz.getSuperclass();
}
}
}
return outcome;
}
private void supportMinOrMaxDimesion(int widthHint, int heightHint, View view, PercentLayoutInfo info) {
try {
Class clazz = view.getClass();
invokeMethod("setMaxWidth", widthHint, heightHint, view, clazz, info.maxWidthPercent);
invokeMethod("setMaxHeight", widthHint, heightHint, view, clazz, info.maxHeightPercent);
invokeMethod("setMinWidth", widthHint, heightHint, view, clazz, info.minWidthPercent);
invokeMethod("setMinHeight", widthHint, heightHint, view, clazz, info.minHeightPercent);
} catch (NoSuchMethodException e) {
e.printStackTrace();
} catch (InvocationTargetException e2) {
e2.printStackTrace();
} catch (IllegalAccessException e3) {
e3.printStackTrace();
}
}
/** @noinspection UnusedParameters*/
private int getDefaultMargin(View c, boolean horizontal, boolean leading) {
if (c.getClass() == Space.class) {
return 0;
}
return mDefaultGap / 2;
}
@SuppressLint({"RestrictedApi"})
private static Object getMenuItemData(View view) throws InvocationTargetException, IllegalAccessException {
if (view.getClass() == sListMenuItemViewClazz) {
return sItemViewGetDataMethod.invoke(view);
} else if (ViewUtil.instanceOfAndroidXListMenuItemView(view) || ViewUtil.instanceOfSupportListMenuItemView(view) || ViewUtil.instanceOfBottomNavigationItemView(view)) {
return ViewUtil.getItemData(view);
}
return null;
}
/**
* Utility method to make getting a View via findViewById() more safe & simple.
* <p/>
* - Casts view to appropriate type based on expected return value
* - Handles & logs invalid casts
*
* @param parentView Parent View containing the view we are trying to get
* @param id R.id value for view
* @return View object, cast to appropriate type based on expected return value.
* @throws ClassCastException if cast to the expected type breaks.
*/
@SuppressWarnings("unchecked")
public static <T extends View> T findViewById(View parentView, int id) {
T view = null;
View genericView = parentView.findViewById(id);
try {
view = (T) (genericView);
} catch (Exception ex) {
String message = "Can't cast view (" + id + ") to a " + view.getClass() + ". Is actually a " + genericView.getClass() + ".";
Log.e("PercolateAndroidUtils", message);
throw new ClassCastException(message);
}
return view;
}
private View get(final int id) {
final View view = test.getActivity().findViewById(id);
if (view == null) {
throw new IllegalArgumentException("No such view: " + id);
}
if (view.getVisibility() != View.VISIBLE) {
throw new IllegalArgumentException("View " + view.getClass() + " is not visible: " + id);
}
return view;
}
/**
* Utility method to make getting a View via findViewById() more safe & simple.
* <p/>
* - Casts view to appropriate type based on expected return value
* - Handles & logs invalid casts
*
* @param context The current Context or Activity that this method is called from
* @param id R.id value for view
* @return View object, cast to appropriate type based on expected return value.
* @throws ClassCastException if cast to the expected type breaks.
*/
@SuppressWarnings("unchecked")
public static <T extends View> T findViewById(Activity context, int id) {
T view = null;
View genericView = context.findViewById(id);
try {
view = (T) (genericView);
} catch (Exception ex) {
String message = "Can't cast view (" + id + ") to a " + view.getClass() + ". Is actually a " + genericView.getClass() + ".";
Log.e("PercolateAndroidUtils", message);
throw new ClassCastException(message);
}
return view;
}
@Nullable
public static StyleHandler get(View view) {
Class<? extends View> vClazz = view.getClass();
StyleHandler styleHandler = sAttrHandlerCache.get(vClazz);
if (styleHandler == null) {
styleHandler = byClass(vClazz);
if (styleHandler != null) {
sAttrHandlerCache.put(vClazz, styleHandler);
}
}
return styleHandler;
}
/**
* Utility method to make getting a View via findViewById() more safe & simple.
* <p/>
* - Casts view to appropriate type based on expected return value
* - Handles & logs invalid casts
*
* @param parentView Parent View containing the view we are trying to get
* @param id R.id value for view
* @return View object, cast to appropriate type based on expected return value.
* @throws ClassCastException if cast to the expected type breaks.
*/
@SuppressWarnings("unchecked")
public static <T extends View> T findViewById(View parentView, int id) {
T view = null;
View genericView = parentView.findViewById(id);
try {
view = (T) (genericView);
} catch (Exception ex) {
String message = "Can't cast view (" + id + ") to a " + view.getClass() + ". Is actually a " + genericView.getClass() + ".";
Log.e("PercolateAndroidUtils", message);
throw new ClassCastException(message);
}
return view;
}
public static boolean canViewScrollVertically(View view, int direction) {
boolean result = false;
if (Build.VERSION.SDK_INT < 14) {
if (view instanceof AbsListView) {//list view etc.
result = performAbsListView((AbsListView) view, direction);
} else {
try {//i known it's a bad way!
Class<? extends View> viewClass = view.getClass();
final int offset = (int) viewClass.getDeclaredMethod("computeVerticalScrollOffset").invoke(view);
final int range = (int) viewClass.getDeclaredMethod("computeVerticalScrollRange").invoke(view)
- (int) viewClass.getDeclaredMethod("computeVerticalScrollExtent").invoke(view);
if (range == 0) return false;
if (direction < 0) {
result = (offset > 0);
} else {
result = offset < range - 1;
}
} catch (Exception e) {
if (DEBUG_SCROLL_CHECK)
L.e(TAG, "no such method!!");
result = view.getScrollY() > 0;
}
}
} else {
result = view.canScrollVertically(direction);
}
if (DEBUG_SCROLL_CHECK)
L.e(TAG, "view = %s , direction is %s, canViewScrollVertically = %s",
view,
(direction > 0 ? "up" : "down"),
result);
return result;
}
public ViewInfosContainer(View view, View parent) {
size = AnimUtils.getViewSize(view);
this.position = AnimUtils.getPositionRelativeTo(view, parent);
padding = new int[]{view.getPaddingLeft(), view.getPaddingTop(), view.getPaddingRight(), view.getPaddingBottom()};
Drawable drawable = view.getBackground();
if (drawable instanceof ColorDrawable) {
backgroundColor = ((ColorDrawable) drawable).getColor();
} else {
backgroundColor = view.getResources().getColor(R.color.transparent);
}
viewId = view.getId();
Object tag = view.getTag();
if (tag != null) {
if (tag instanceof Parcelable) {
this.viewTagP = (Parcelable) tag;
} else if (tag instanceof Serializable) {
this.viewTagS = (Serializable) tag;
}
}
viewClass = view.getClass();
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
this.elevation = AnimUtils.getElevationRelativeTo(view, parent);
}
if (view instanceof TextView) {
textColor = ((TextView) view).getCurrentTextColor();
textSize = ((TextView) view).getTextSize();
textGravity = ((TextView) view).getGravity();
}
}
private void addProperties(JsonWriter j, View v)
throws IOException {
final Class<?> viewClass = v.getClass();
for (final PropertyDescription desc : mProperties) {
if (desc.targetClass.isAssignableFrom(viewClass) && null != desc.accessor) {
final Object value = desc.accessor.applyMethod(v);
if (null == value) {
// Don't produce anything in this case
} else if (value instanceof Number) {
j.name(desc.name).value((Number) value);
} else if (value instanceof Boolean) {
boolean clickable = (boolean) value;
if (TextUtils.equals("clickable", desc.name)) {
if (VisualUtil.isSupportClick(v)) {
clickable = true;
} else if (VisualUtil.isForbiddenClick(v)) {
clickable = false;
}
}
j.name(desc.name).value(clickable);
} else if (value instanceof ColorStateList) {
j.name(desc.name).value((Integer) ((ColorStateList) value).getDefaultColor());
} else if (value instanceof Drawable) {
final Drawable drawable = (Drawable) value;
final Rect bounds = drawable.getBounds();
j.name(desc.name);
j.beginObject();
j.name("classes");
j.beginArray();
Class klass = drawable.getClass();
while (klass != Object.class) {
j.value(klass.getCanonicalName());
klass = klass.getSuperclass();
}
j.endArray();
j.name("dimensions");
j.beginObject();
j.name("left").value(bounds.left);
j.name("right").value(bounds.right);
j.name("top").value(bounds.top);
j.name("bottom").value(bounds.bottom);
j.endObject();
if (drawable instanceof ColorDrawable) {
final ColorDrawable colorDrawable = (ColorDrawable) drawable;
j.name("color").value(colorDrawable.getColor());
}
j.endObject();
} else {
j.name(desc.name).value(value.toString());
}
}
}
}
private static boolean isDecorView(@NonNull View view) {
Class<?> clazz = view.getClass();
return clazz.getAnnotation(DecorView.class) != null;
}
private static boolean isDecorView(@NonNull View view) {
Class<?> clazz = view.getClass();
return clazz.getAnnotation(DecorView.class) != null;
}