下面列出了android.view.View#getResources ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* copied from https://groups.google.com/forum/?utm_medium=email&utm_source=footer#!searchin/android-test-kit-discuss/ActionBar/android-test-kit-discuss/mlMbTR30-0U/WljZkKBbdU0J
* @param resourceNameMatcher a view matcher
* @return a view matcher
*/
public static Matcher<View> withResourceName(final Matcher<String> resourceNameMatcher)
{
return new TypeSafeMatcher<View>()
{
@Override
public void describeTo(Description description)
{
description.appendText("with resource name: ");
resourceNameMatcher.describeTo(description);
}
@Override
public boolean matchesSafely(View view)
{
int id = view.getId();
return ((id != View.NO_ID) && (id != 0) && (view.getResources() != null)
&& (resourceNameMatcher.matches(view.getResources().getResourceName(id))));
}
};
}
/**
* Returns a String description of the given {@link View}. The default is to return the view's
* resource entry name.
*
* @param view the {@link View} to describe
* @return a String description of the given {@link View}
*/
public String describeView(@Nullable View view) {
StringBuilder message = new StringBuilder();
if ((view != null
&& view.getId() != View.NO_ID
&& view.getResources() != null
&& !ViewAccessibilityUtils.isViewIdGenerated(view.getId()))) {
message.append("View ");
try {
message.append(view.getResources().getResourceEntryName(view.getId()));
} catch (Exception e) {
/* In some integrations (seen in Robolectric), the resources may behave inconsistently */
message.append("with no valid resource name");
}
} else {
message.append("View with no valid resource name");
}
return message.toString();
}
/**
* @param view The {@link View} to identify
* @return a {@link String} resource name for the provided {@code view} in the format
* "package:type/entry", or {@code null} if a resource name does not exist or cannot be
* resolved.
*/
public static @Nullable String getResourceNameForView(View view) {
if ((view == null) || (view.getId() == View.NO_ID) || (view.getResources() == null)) {
return null;
}
if (!isViewIdGenerated(view.getId())) {
try {
return view.getResources().getResourceName(view.getId());
} catch (Resources.NotFoundException nfe) {
// Do nothing -- Potential test environment issue
LogUtils.w(TAG, "Unable to resolve resource name from view ID.");
}
}
return null;
}
private void setItemBackgroundColor(View itemView) {
final Resources.Theme theme = itemView.getContext()
.getTheme();
final Resources res = itemView.getResources();
int color;
if (getLayoutPosition() % 2 == 0) {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
color = res.getColor(displayable.getThemeManager()
.getAttributeForTheme(R.attr.backgroundSecondary).resourceId, theme);
} else {
color = res.getColor(displayable.getThemeManager()
.getAttributeForTheme(R.attr.backgroundSecondary).resourceId);
}
} else {
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
color = res.getColor(displayable.getThemeManager()
.getAttributeForTheme(R.attr.backgroundMain).resourceId, theme);
} else {
color = res.getColor(displayable.getThemeManager()
.getAttributeForTheme(R.attr.backgroundMain).resourceId);
}
}
itemView.setBackgroundColor(color);
}
public SetupStep(final int stepNo, final String applicationName, final TextView bulletView,
final View stepView, final int title, final int instruction,
final int finishedInstruction, final int actionIcon, final int actionLabel) {
mStepNo = stepNo;
mStepView = stepView;
mBulletView = bulletView;
final Resources res = stepView.getResources();
mActivatedColor = res.getColor(R.color.setup_text_action);
mDeactivatedColor = res.getColor(R.color.setup_text_dark);
final TextView titleView = mStepView.findViewById(R.id.setup_step_title);
titleView.setText(res.getString(title, applicationName));
mInstruction = (instruction == 0) ? null
: res.getString(instruction, applicationName);
mFinishedInstruction = (finishedInstruction == 0) ? null
: res.getString(finishedInstruction, applicationName);
mActionLabel = mStepView.findViewById(R.id.setup_step_action_label);
mActionLabel.setText(res.getString(actionLabel));
if (actionIcon == 0) {
final int paddingEnd = mActionLabel.getPaddingEnd();
mActionLabel.setPaddingRelative(paddingEnd, 0, paddingEnd, 0);
} else {
mActionLabel.setCompoundDrawablesRelativeWithIntrinsicBounds(
res.getDrawable(actionIcon), null, null, null);
}
}
private void captureValues(@NonNull TransitionValues transitionValues) {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
return;
}
View view = transitionValues.view;
if (view.getWidth() <= 0 || view.getHeight() <= 0) {
return;
}
Rect bounds = new Rect(0, 0, view.getWidth(), view.getHeight());
if (mFadeBehavior != FADE_BEHAVIOR_REVEAL) {
bounds.offset(view.getLeft(), view.getTop());
}
transitionValues.values.put(PROPNAME_BOUNDS, bounds);
if (Transition.DBG) {
Log.d(LOG_TAG, "Captured bounds " + transitionValues.values.get(PROPNAME_BOUNDS));
}
Bitmap bitmap = Bitmap.createBitmap(view.getWidth(), view.getHeight(),
Bitmap.Config.ARGB_8888);
if (view instanceof TextureView) {
bitmap = ((TextureView) view).getBitmap();
} else {
Canvas c = new Canvas(bitmap);
view.draw(c);
}
transitionValues.values.put(PROPNAME_BITMAP, bitmap);
BitmapDrawable drawable = new BitmapDrawable(view.getResources(), bitmap);
// TODO: lrtb will be wrong if the view has transXY set
drawable.setBounds(bounds);
transitionValues.values.put(PROPNAME_DRAWABLE, drawable);
}
public static Matcher<View> withFirstId(final int id) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
boolean found = false;
@Override
public void describeTo(Description description) {
String idDescription = Integer.toString(id);
if (resources != null) {
try {
idDescription = resources.getResourceName(id);
} catch (Resources.NotFoundException e) {
// No big deal, will just use the int value.
idDescription = String.format("%s (resource name not found)", id);
}
}
description.appendText("with id: " + idDescription);
}
@Override
public boolean matchesSafely(View view) {
if (found) return false;
resources = view.getResources();
if (id == view.getId()) {
found = true;
return true;
}
return false;
}
};
}
public BlurTask(View target, BlurFactor factor, Callback callback) {
target.setDrawingCacheEnabled(true);
this.res = target.getResources();
this.factor = factor;
this.callback = callback;
target.destroyDrawingCache();
target.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
capture = target.getDrawingCache();
contextWeakRef = new WeakReference<>(target.getContext());
}
public static int parseColor(View view, String text) {
if (text.startsWith("@color/")) {
Resources resources = view.getResources();
return resources.getColor(resources.getIdentifier(text.substring("@color/".length()), "color", view.getContext().getPackageName()));
}
if (text.length() == 4 && text.startsWith("#")) {
text = "#" + text.charAt(1) + text.charAt(1) + text.charAt(2) + text.charAt(2) + text.charAt(3) + text.charAt(3);
}
return Color.parseColor(text);
}
public static int parseColor(View view, String text) {
if (text.startsWith("@color/")) {
Resources resources = view.getResources();
return resources.getColor(resources.getIdentifier(text.substring("@color/".length()), "color", view.getContext().getPackageName()));
}
if (text.length() == 4 && text.startsWith("#")) {
text = "#" + text.charAt(1) + text.charAt(1) + text.charAt(2) + text.charAt(2) + text.charAt(3) + text.charAt(3);
}
return Color.parseColor(text);
}
public ImageGetterAsyncTask(UrlDrawable d, HtmlHttpImageGetter imageGetter, View container,
boolean matchParentWidth, boolean compressImage, int qualityImage) {
this.drawableReference = new WeakReference<>(d);
this.imageGetterReference = new WeakReference<>(imageGetter);
this.containerReference = new WeakReference<>(container);
this.resources = new WeakReference<>(container.getResources());
this.matchParentWidth = matchParentWidth;
this.compressImage = compressImage;
this.qualityImage = qualityImage;
}
public BlurTask(View target, BlurFactor factor, Callback callback) {
target.setDrawingCacheEnabled(true);
this.res = target.getResources();
this.factor = factor;
this.callback = callback;
target.destroyDrawingCache();
target.setDrawingCacheQuality(View.DRAWING_CACHE_QUALITY_LOW);
capture = target.getDrawingCache();
contextWeakRef = new WeakReference<>(target.getContext());
}
public static void startAnimators(final View view, int startOffsetX, int startOffsetY, long delay) {
if (view.getVisibility() == View.VISIBLE && view.getAlpha() != 0f) {
view.clearAnimation();
view.animate().cancel();
final Resources res = view.getResources();
final float endAlpha = view.getAlpha();
final float endTranslateX = view.getTranslationX();
final float endTranslateY = view.getTranslationY();
view.setAlpha(0);
final Animator fade = ObjectAnimator.ofFloat(view, View.ALPHA, endAlpha);
fade.setDuration(res.getInteger(R.integer.material_in_fade_anim_duration));
fade.setInterpolator(new AccelerateInterpolator());
fade.setStartDelay(delay);
fade.start();
ViewPropertyAnimator slide = view.animate();
if (startOffsetY != 0) {
view.setTranslationY(startOffsetY);
slide.translationY(endTranslateY);
} else {
view.setTranslationX(startOffsetX);
slide.translationX(endTranslateX);
}
slide.setInterpolator(new DecelerateInterpolator(2));
slide.setDuration(res.getInteger(R.integer.material_in_slide_anim_duration));
slide.setStartDelay(delay);
slide.setListener(new AnimatorListenerAdapter() {
@Override
public void onAnimationCancel(Animator animation) {
if (fade.isStarted()) {
fade.cancel();
}
view.setAlpha(endAlpha);
view.setTranslationX(endTranslateX);
view.setTranslationY(endTranslateY);
}
});
slide.start();
}
}
public Matcher<View> atPositionOnView(final int position, final int targetViewId) {
return new TypeSafeMatcher<View>() {
Resources resources;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (this.resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%s (resource name not found)",
recyclerViewId);
}
}
description.appendText("RecyclerView with id: "
+ idDescription
+ " at position: "
+ position);
}
public boolean matchesSafely(View view) {
this.resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView =
(RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
RecyclerView.ViewHolder viewHolder = recyclerView.
findViewHolderForAdapterPosition(position);
if (viewHolder != null) {
childView = viewHolder.itemView;
}
} else {
return false;
}
}
if (targetViewId == -1) {
return view.equals(childView);
} else {
View targetView = childView.findViewById(targetViewId);
return view.equals(targetView);
}
}
};
}
private static String viewToString(View view) {
StringBuilder out = new StringBuilder(128);
out.append(view.getClass().getName());
out.append('{');
out.append(Integer.toHexString(System.identityHashCode(view)));
out.append(' ');
switch (view.getVisibility()) {
case View.VISIBLE: out.append('V'); break;
case View.INVISIBLE: out.append('I'); break;
case View.GONE: out.append('G'); break;
default: out.append('.'); break;
}
out.append(view.isFocusable() ? 'F' : '.');
out.append(view.isEnabled() ? 'E' : '.');
out.append(view.willNotDraw() ? '.' : 'D');
out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
out.append(view.isClickable() ? 'C' : '.');
out.append(view.isLongClickable() ? 'L' : '.');
out.append(' ');
out.append(view.isFocused() ? 'F' : '.');
out.append(view.isSelected() ? 'S' : '.');
out.append(view.isPressed() ? 'P' : '.');
out.append(' ');
out.append(view.getLeft());
out.append(',');
out.append(view.getTop());
out.append('-');
out.append(view.getRight());
out.append(',');
out.append(view.getBottom());
final int id = view.getId();
if (id != View.NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = view.getResources();
if (id != 0 && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
out.append("}");
return out.toString();
}
public static void setupDefaultForeground(View view, Integer color, Integer alpha) {
if (view instanceof IForeground && ((IForeground) view).hasForeground() == false && view.getResources() != null) {
setupForeground(view, view.getResources().getDrawable(R.drawable.lv_click_foreground), color, alpha);
}
}
public Matcher<View> atPositionOnView(final int position, final int targetViewId) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (this.resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%s (resource name not found)",
new Object[] { Integer.valueOf
(recyclerViewId) });
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
this.resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView =
(RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
childView = recyclerView.findViewHolderForAdapterPosition(position).itemView;
}
else {
return false;
}
}
if (targetViewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(targetViewId);
return view == targetView;
}
}
};
}
public Matcher<View> atPositionOnView(final int position, final int targetViewId) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (this.resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%s (resource name not found)",
new Object[] { Integer.valueOf
(recyclerViewId) });
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
this.resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView =
(RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
childView = recyclerView.findViewHolderForAdapterPosition(position).itemView;
}
else {
return false;
}
}
if (targetViewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(targetViewId);
return view == targetView;
}
}
};
}
public static Matcher<View> atPositionOnRecyclerView(final int recyclerViewId,
final int position,
final int targetViewId) {
return new TypeSafeMatcher<View>() {
Resources resources = null;
View childView;
public void describeTo(Description description) {
String idDescription = Integer.toString(recyclerViewId);
if (this.resources != null) {
try {
idDescription = this.resources.getResourceName(recyclerViewId);
} catch (Resources.NotFoundException var4) {
idDescription = String.format("%s (resource name not found)",
new Object[]{Integer.valueOf
(recyclerViewId)});
}
}
description.appendText("with id: " + idDescription);
}
public boolean matchesSafely(View view) {
this.resources = view.getResources();
if (childView == null) {
RecyclerView recyclerView =
(RecyclerView) view.getRootView().findViewById(recyclerViewId);
if (recyclerView != null && recyclerView.getId() == recyclerViewId) {
childView = recyclerView.findViewHolderForAdapterPosition(position).itemView;
} else {
return false;
}
}
if (targetViewId == -1) {
return view == childView;
} else {
View targetView = childView.findViewById(targetViewId);
return view == targetView;
}
}
};
}
private static String viewToString(View view) {
StringBuilder out = new StringBuilder(128);
out.append(view.getClass().getName());
out.append('{');
out.append(Integer.toHexString(System.identityHashCode(view)));
out.append(' ');
switch (view.getVisibility()) {
case View.VISIBLE: out.append('V'); break;
case View.INVISIBLE: out.append('I'); break;
case View.GONE: out.append('G'); break;
default: out.append('.'); break;
}
out.append(view.isFocusable() ? 'F' : '.');
out.append(view.isEnabled() ? 'E' : '.');
out.append(view.willNotDraw() ? '.' : 'D');
out.append(view.isHorizontalScrollBarEnabled()? 'H' : '.');
out.append(view.isVerticalScrollBarEnabled() ? 'V' : '.');
out.append(view.isClickable() ? 'C' : '.');
out.append(view.isLongClickable() ? 'L' : '.');
out.append(' ');
out.append(view.isFocused() ? 'F' : '.');
out.append(view.isSelected() ? 'S' : '.');
out.append(view.isPressed() ? 'P' : '.');
out.append(' ');
out.append(view.getLeft());
out.append(',');
out.append(view.getTop());
out.append('-');
out.append(view.getRight());
out.append(',');
out.append(view.getBottom());
final int id = view.getId();
if (id != View.NO_ID) {
out.append(" #");
out.append(Integer.toHexString(id));
final Resources r = view.getResources();
if (id != 0 && r != null) {
try {
String pkgname;
switch (id&0xff000000) {
case 0x7f000000:
pkgname="app";
break;
case 0x01000000:
pkgname="android";
break;
default:
pkgname = r.getResourcePackageName(id);
break;
}
String typename = r.getResourceTypeName(id);
String entryname = r.getResourceEntryName(id);
out.append(" ");
out.append(pkgname);
out.append(":");
out.append(typename);
out.append("/");
out.append(entryname);
} catch (Resources.NotFoundException e) {
}
}
}
out.append("}");
return out.toString();
}