下面列出了怎么用android.content.res.Resources的API类实例代码及写法,或者点击链接到github查看源代码。
/**
* 获取导航栏高度
*
* @param context
* @return
*/
public static int getNavigationBarHeight(Context context) {
boolean hasMenuKey = ViewConfiguration.get(context).hasPermanentMenuKey();
boolean hasBackKey = KeyCharacterMap.deviceHasKey(KeyEvent.KEYCODE_BACK);
if (!hasMenuKey && !hasBackKey) {
//没有物理按钮(虚拟导航栏)
print("没有物理按钮(虚拟导航栏)");
Resources resources = context.getResources();
int resourceId = resources.getIdentifier("navigation_bar_height", "dimen", "android");
//获取NavigationBar的高度
int height = resources.getDimensionPixelSize(resourceId);
return height;
} else {
print("有物理导航栏,小米非全面屏");
//有物理导航栏,小米非全面屏
return 0;
}
}
@Override
public void inflate(Resources res, XmlPullParser parser, AttributeSet attrs, Theme theme)
throws XmlPullParserException, IOException {
final VectorDrawableState state = mVectorState;
final VPathRenderer pathRenderer = new VPathRenderer();
state.mVPathRenderer = pathRenderer;
final TypedArray a = obtainAttributes(res, theme, attrs, R.styleable.VectorDrawable);
updateStateFromTypedArray(a);
a.recycle();
state.mCacheDirty = true;
inflateInternal(res, parser, attrs, theme);
mTintFilter = updateTintFilter(mTintFilter, state.mTint, state.mTintMode);
}
private static void addEmotions(SpannableString value) {
// Paint.FontMetrics fontMetrics = mEditText.getPaint().getFontMetrics();
// int size = (int)(fontMetrics.descent-fontMetrics.ascent);
int size = 50;
Map<String, Integer> smiles = SmileyMap.getInstance().getSmiles();
Resources resources = BeeboApplication.getAppContext().getResources();
Matcher localMatcher = EMOTION_URL.matcher(value);
while (localMatcher.find()) {
String key = localMatcher.group(0);
if (smiles.containsKey(key)) {
int k = localMatcher.start();
int m = localMatcher.end();
if (m - k < 8) {
Drawable drawable = resources.getDrawable(smiles.get(key));
if (drawable != null) {
drawable.setBounds(0, 0, size, size);
}
ImageSpan localImageSpan = new ImageSpan(drawable, ImageSpan.ALIGN_BASELINE);
value.setSpan(localImageSpan, k, m, Spanned.SPAN_INCLUSIVE_EXCLUSIVE);
}
}
}
}
public static Sound[] getSounds(Context context) {
Resources res = context.getApplicationContext().getResources();
TypedArray labels = res.obtainTypedArray(R.array.labels);
TypedArray ids = res.obtainTypedArray(R.array.ids);
Sound[] sounds = new Sound[labels.length()];
for (int i = 0; i < sounds.length; i++) {
sounds[i] = new Sound(labels.getString(i), ids.getResourceId(i, -1));
}
labels.recycle();
ids.recycle();
return sounds;
}
private HolographicOutlineHelper(Context context) {
Resources res = context.getResources();
float mediumBlur = res.getDimension(R.dimen.blur_size_medium_outline);
mMediumOuterBlurMaskFilter = new BlurMaskFilter(mediumBlur, BlurMaskFilter.Blur.OUTER);
mMediumInnerBlurMaskFilter = new BlurMaskFilter(mediumBlur, BlurMaskFilter.Blur.NORMAL);
mThinOuterBlurMaskFilter = new BlurMaskFilter(
res.getDimension(R.dimen.blur_size_thin_outline), BlurMaskFilter.Blur.OUTER);
mShadowBlurMaskFilter = new BlurMaskFilter(
res.getDimension(R.dimen.blur_size_click_shadow), BlurMaskFilter.Blur.NORMAL);
mDrawPaint.setFilterBitmap(true);
mDrawPaint.setAntiAlias(true);
mBlurPaint.setFilterBitmap(true);
mBlurPaint.setAntiAlias(true);
mErasePaint.setXfermode(new PorterDuffXfermode(PorterDuff.Mode.DST_OUT));
mErasePaint.setFilterBitmap(true);
mErasePaint.setAntiAlias(true);
}
public static String getDisplayMetricsDesc() {
DisplayMetrics curDisplayMetrics = null;
Resources res = null;
int swdp = 0;
if (sContext != null) {
res = sContext.getResources();
}
if (res != null) {
curDisplayMetrics = res.getDisplayMetrics();
swdp = res.getConfiguration().smallestScreenWidthDp;
}
StringBuilder sb = new StringBuilder();
sb.append("当前显示信息:").append(curDisplayMetrics)
.append(" --> 实际显示信息:").append(displayMetrics)
.append(" 最短宽 dpi:").append(swdp)
;
return sb.toString();
}
public static WindowManager.LayoutParams createLayoutParams(Context context) {
Resources res = context.getResources();
int width = res.getDimensionPixelSize(R.dimen.data_inspector_menu_width);
final WindowManager.LayoutParams params =
new WindowManager.LayoutParams(width, WRAP_CONTENT, TYPE_SYSTEM_ERROR,
FLAG_NOT_FOCUSABLE | FLAG_NOT_TOUCH_MODAL | FLAG_LAYOUT_NO_LIMITS
| FLAG_LAYOUT_INSET_DECOR | FLAG_LAYOUT_IN_SCREEN, TRANSLUCENT);
params.y = res.getDimensionPixelSize(R.dimen.data_inspector_toolbar_height);
if (Build.VERSION.SDK_INT == 23) { // MARSHMALLOW
params.y = res.getDimensionPixelSize(R.dimen.data_inspector_toolbar_height_m);
}
params.gravity = Gravity.TOP | Gravity.RIGHT;
return params;
}
public QrCodeFinderView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
mPaint = new Paint();
Resources resources = getResources();
mMaskColor = resources.getColor(R.color.qr_code_finder_mask);
mFrameColor = resources.getColor(R.color.qr_code_finder_frame);
mLaserColor = resources.getColor(R.color.qr_code_finder_laser);
mTextColor = resources.getColor(R.color.qr_code_white);
mFocusThick = 1;
mAngleThick = 8;
mAngleLength = 40;
mScannerAlpha = 0;
init(context);
}
private Drawable resolveResource() {
Resources rsrc = getResources();
if (rsrc == null) {
return null;
}
Drawable d = null;
if (mResource != 0) {
try {
d = rsrc.getDrawable(mResource);
} catch (Exception e) {
Log.w(TAG, "Unable to find resource: " + mResource, e);
// Don't try again.
mResource = 0;
}
}
return RoundedDrawable.fromDrawable(d);
}
public FingerprintHelper initialize(@NonNull Resources resources) {
if (mAuthenticator != null) return this;
sensorMissing = resources.getString(R.string.fingerprint_sensor_hardware_missing);
fingerprintNotSetup = resources.getString(R.string.fingerprint_not_set_up);
// Try Pass first
try {
mAuthenticator = new SamsungPass();
registerAuthenticator(mAuthenticator);
} catch (Exception e) {
// nothing to do. Try native next
logger.debug("Couldn't use Pass. Trying native fingerprint.");
}
// Native fingerprint is supported on M+ only.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
registerAuthenticator(new NativeFingerprint());
}
return this;
}
private void upgradeAutocorrectionSettings(final SharedPreferences prefs, final Resources res) {
final String thresholdSetting =
prefs.getString(PREF_AUTO_CORRECTION_THRESHOLD_OBSOLETE, null);
if (thresholdSetting != null) {
SharedPreferences.Editor editor = prefs.edit();
editor.remove(PREF_AUTO_CORRECTION_THRESHOLD_OBSOLETE);
final String autoCorrectionOff =
res.getString(R.string.auto_correction_threshold_mode_index_off);
if (thresholdSetting.equals(autoCorrectionOff)) {
editor.putBoolean(PREF_AUTO_CORRECTION, false);
} else {
editor.putBoolean(PREF_AUTO_CORRECTION, true);
}
editor.commit();
}
}
@TargetApi(14)
private int getNavigationBarHeight(Context context) {
Resources res = context.getResources();
int result = 0;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
if (hasNavBar(context)) {
String key;
if (mInPortrait) {
key = NAV_BAR_HEIGHT_RES_NAME;
} else {
key = NAV_BAR_HEIGHT_LANDSCAPE_RES_NAME;
}
return getInternalDimensionSize(res, key);
}
}
return result;
}
/**
* Execute {@link #job(Resources)} method in specified system locale exclusively.
*
* @param res the resources to use.
* @param newLocale the locale to change to. Run in system locale if null.
* @return the value returned from {@link #job(Resources)}.
*/
public T runInLocale(final Resources res, final Locale newLocale) {
synchronized (sLockForRunInLocale) {
final Configuration conf = res.getConfiguration();
if (newLocale == null || newLocale.equals(conf.locale)) {
return job(res);
}
final Locale savedLocale = conf.locale;
try {
conf.locale = newLocale;
res.updateConfiguration(conf, null);
return job(res);
} finally {
conf.locale = savedLocale;
res.updateConfiguration(conf, null);
}
}
}
public @Nullable String getDescription() {
final Resources res = Resources.getSystem();
if ((flags & FLAG_SD) != 0) {
if (isInteresting(label)) {
return res.getString(com.android.internal.R.string.storage_sd_card_label, label);
} else {
return res.getString(com.android.internal.R.string.storage_sd_card);
}
} else if ((flags & FLAG_USB) != 0) {
if (isInteresting(label)) {
return res.getString(com.android.internal.R.string.storage_usb_drive_label, label);
} else {
return res.getString(com.android.internal.R.string.storage_usb_drive);
}
} else {
return null;
}
}
private void initFastScrollerEx(Context context, AttributeSet attrs, int defStyleAttr) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.RecyclerView,
defStyleAttr, 0);
StateListDrawable verticalThumbDrawable = (StateListDrawable) a
.getDrawable(R.styleable.RecyclerView_fastScrollVerticalThumbDrawable);
Drawable verticalTrackDrawable = a
.getDrawable(R.styleable.RecyclerView_fastScrollVerticalTrackDrawable);
StateListDrawable horizontalThumbDrawable = (StateListDrawable) a
.getDrawable(R.styleable.RecyclerView_fastScrollHorizontalThumbDrawable);
Drawable horizontalTrackDrawable = a
.getDrawable(R.styleable.RecyclerView_fastScrollHorizontalTrackDrawable);
Resources resources = getContext().getResources();
new FastScrollerEx(this, verticalThumbDrawable, verticalTrackDrawable,
horizontalThumbDrawable, horizontalTrackDrawable,
resources.getDimensionPixelSize(R.dimen.fastscroll_default_thickness),
resources.getDimensionPixelSize(R.dimen.fastscroll_minimum_range),
resources.getDimensionPixelOffset(R.dimen.fastscroll_margin));
}
public float pixel2dip(Context context, float n){
Resources resources = context.getResources();
DisplayMetrics metrics = resources.getDisplayMetrics();
float dp = n / (metrics.densityDpi / 160f);
return dp;
}
public void init(List<Integer> milliliter) {
if (null == milliliter || milliliter.size() == 0)
return;
this.milliliter = delZero(milliliter);
Resources res = getResources();
tb = res.getDimension(R.dimen.historyscore_tb);
interval_left_right = tb * 2.0f;
interval_left = tb * 0.5f;
paint_date = new Paint();
paint_date.setStrokeWidth(tb * 0.1f);
paint_date.setTextSize(tb * 1.2f);
paint_date.setColor(fineLineColor);
paint_brokenLine = new Paint();
paint_brokenLine.setStrokeWidth(tb * 0.1f);
paint_brokenLine.setColor(blueLineColor);
paint_brokenLine.setAntiAlias(true);
paint_dottedline = new Paint();
paint_dottedline.setStyle(Paint.Style.STROKE);
paint_dottedline.setColor(fineLineColor);
paint_brokenline_big = new Paint();
paint_brokenline_big.setStrokeWidth(tb * 0.4f);
paint_brokenline_big.setColor(fineLineColor);
paint_brokenline_big.setAntiAlias(true);
framPanint = new Paint();
framPanint.setAntiAlias(true);
framPanint.setStrokeWidth(2f);
path = new Path();
bitmap_point = BitmapFactory.decodeResource(getResources(),
R.drawable.wire_frame_icon_point_blue);
setLayoutParams(new LayoutParams(
(int) (this.milliliter.size() * interval_left_right),
LayoutParams.MATCH_PARENT));
}
static String getAppIdFromResource(Context ctx) {
try {
Resources res = ctx.getResources();
String pkgName = ctx.getPackageName();
int res_id = res.getIdentifier("app_id", "string", pkgName);
return res.getString(res_id);
} catch (Exception ex) {
ex.printStackTrace();
return "??? (failed to retrieve APP ID)";
}
}
/**
* Create a VectorDrawableCompat from inside an XML document using an optional
* {@link Resources.Theme}. Called on a parser positioned at a tag in an XML
* document, tries to create a Drawable from that tag. Returns {@code null}
* if the tag is not a valid drawable.
*/
@SuppressLint("NewApi")
public static VectorDrawableCompat createFromXmlInner(Resources r, XmlPullParser parser,
AttributeSet attrs, Resources.Theme theme) throws XmlPullParserException, IOException {
final VectorDrawableCompat drawable = new VectorDrawableCompat();
drawable.inflate(r, parser, attrs, theme);
return drawable;
}
public MonthPickerView(Context context, AttributeSet attrs) {
super(context, attrs);
Resources res = context.getResources();
mShortMonthLabels = new DateFormatSymbols().getShortMonths();
mNormalTextColor = getColor(context, R.color.bsp_text_color_primary_light);
// Same as background color
mSelectedMonthTextColor = getColor(context, R.color.bsp_date_picker_view_animator);
mCurrentMonthTextColor = Utils.getThemeAccentColor(context);
mDisabledMonthTextColor = getColor(context, R.color.bsp_text_color_disabled_light);
Calendar now = Calendar.getInstance();
mCurrentMonth = now.get(Calendar.MONTH);
mCurrentYear = now.get(Calendar.YEAR);
MONTH_LABEL_TEXT_SIZE = res.getDimensionPixelSize(R.dimen.bsp_month_picker_month_label_size);
MONTH_SELECTED_CIRCLE_SIZE = res.getDimensionPixelSize(R.dimen.bsp_month_select_circle_radius);
mRowHeight = (res.getDimensionPixelOffset(R.dimen.bsp_date_picker_view_animator_height)
- MONTH_NAVIGATION_BAR_SIZE) / NUM_ROWS;
mEdgePadding = res.getDimensionPixelSize(R.dimen.bsp_month_view_edge_padding);
// TODO: Set up accessibility components.
// Sets up any standard paints that will be used
initView();
}
/**
* 获取虚拟按键的高度
*
* @param context
* @return
*/
public static int getNavigationBarHeight(Context context) {
int result = 0;
if (hasNavigationBar(context)) {
Resources res = context.getResources();
int resourceId = res.getIdentifier("navigation_bar_height", "dimen", "android");
if (resourceId > 0) {
result = res.getDimensionPixelSize(resourceId);
}
}
return result;
}
/**
* Return the feature bits set by default on a window.
* @param context The context used to access resources
*/
public static int getDefaultFeatures(Context context) {
int features = 0;
final Resources res = context.getResources();
if (res.getBoolean(com.android.internal.R.bool.config_defaultWindowFeatureOptionsPanel)) {
features |= 1 << FEATURE_OPTIONS_PANEL;
}
if (res.getBoolean(com.android.internal.R.bool.config_defaultWindowFeatureContextMenu)) {
features |= 1 << FEATURE_CONTEXT_MENU;
}
return features;
}
/**
* Creates a custom Bitmap containing a letter, digit, or default image (if no letter
* or digit can be resolved), positioned at the center, with a randomized background
* color, picked from {@link #colors}, based on the hashed value of the given string.
*
* @param displayName Any string value
* @return {@link Bitmap}
*/
public Bitmap getLetterTile(String displayName) {
// Don't allow empty strings
if (displayName == null || displayName.length() == 0) { return null; }
final char firstChar = displayName.charAt(0);
// Create a Bitmap with the width & height specified from resources
final Bitmap bitmap = Bitmap.createBitmap(tileSize, tileSize, Bitmap.Config.ARGB_8888);
// Setup our canvas for drawing
final Canvas c = canvas;
c.setBitmap(bitmap);
c.drawColor(pickColor(displayName));
// We want to use the default Bitmap if our character is not a letter or digit
if (Character.isLetterOrDigit(firstChar)) {
this.firstChar[0] = Character.toUpperCase(firstChar);
// Set the paint text size as half the bitmap's height
this.paint.setTextSize(tileSize >> 1);
// Measure the bounds of our first character
this.paint.getTextBounds(this.firstChar, 0, 1, bounds);
// Draw the character on the Canvas
c.drawText(this.firstChar, 0, 1,
tileSize / 2,
tileSize / 2 + (bounds.bottom - bounds.top) / 2,
paint);
} else {
// (32 - 24) / 2 = 4
final float density = Resources.getSystem().getDisplayMetrics().density;
final float defSize = (4f * density);
c.drawBitmap(defaultBitmap, defSize, defSize, null);
}
return bitmap;
}
@Nullable
public static String getString(int resId, Context context) {
try {
return context.getString(resId);
} catch (Resources.NotFoundException e) {
return null;
}
}
/**
* turn an array of resource-colors (contains resource-id integers) into an
* array list of actual color integers
*
* @param r
* @param colors an integer array of resource id's of colors
* @return
*/
public static List<Integer> createColors(Resources r, int[] colors) {
List<Integer> result = new ArrayList<Integer>();
for (int i : colors) {
result.add(r.getColor(i));
}
return result;
}
public static int getScriptId(final Resources resources,
@Nonnull final InputMethodSubtype subtype) {
final Integer value = sScriptIdsForSubtypes.get(subtype);
if (null == value) {
final int scriptId = Builder.readScriptId(resources, subtype);
sScriptIdsForSubtypes.put(subtype, scriptId);
return scriptId;
}
return value;
}
private CharSequence getTopText(long occupancy, final String suffix) {
final String str = String.valueOf(occupancy) + "\n" + suffix;
final int len = str.length();
final int lenFx = len - suffix.length();
final Resources resources = getResources();
SpannableString span = new SpannableString(str);
span.setSpan(new AbsoluteSizeSpan(resources.getDimensionPixelSize(R.dimen.font_20)),
0, lenFx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
span.setSpan(new ForegroundColorSpan(resources.getColor(R.color.white_alpha_224)),
0, lenFx, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
return span;
}
@Test
public void testHasVisibleCustomDrawable() {
final Resources resources = getApplicationContext().getResources();
final Drawable customDrawable = resources.getDrawable(R.drawable.custom_drawable);
final Predicate<View> hasVisibleDrawable = ViewPredicates.hasVisibleDrawable(customDrawable);
assertThat(hasVisibleDrawable.apply(mImageViewWithCustomDrawable)).isTrue();
mImageViewWithCustomDrawable.setVisibility(View.GONE);
assertThat(hasVisibleDrawable.apply(mImageViewWithCustomDrawable)).isFalse();
}
/**
* Update the background color of the mBgCircle image view.
*/
public void setBackgroundColorResource(int colorRes) {
if (getBackground() instanceof ShapeDrawable) {
final Resources res = getResources();
((ShapeDrawable) getBackground()).getPaint().setColor(res.getColor(colorRes));
}
}
/**
* Display the error dialog of not connect device.
*
* @param name device name
*/
private void showErrorDialogNotConnect(final String name) {
Resources res = getActivity().getResources();
String message;
if (name == null) {
message = res.getString(R.string.heart_rate_setting_dialog_error_message,
getString(R.string.heart_rate_setting_default_name));
} else {
message = res.getString(R.string.heart_rate_setting_dialog_error_message, name);
}
showErrorDialog(message);
}