下面列出了android.content.res.Resources#Theme() 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
private void adjustResourceLightness() {
// change up button to light version if using dark theme
int color = 0xFFFFFF;
final Resources.Theme theme = getActivity().getTheme();
if (theme != null) {
TypedArray backgroundAttributes = theme.obtainStyledAttributes(
new int[] { android.R.attr.colorBackground });
if (backgroundAttributes != null) {
color = backgroundAttributes.getColor(0, 0xFFFFFF);
backgroundAttributes.recycle();
}
}
// convert to greyscale and check if < 128
if (color != 0xFFFFFF && 0.21 * Color.red(color) +
0.72 * Color.green(color) +
0.07 * Color.blue(color) < 128) {
mBtnNavUp.setImageResource(R.drawable.navigation_up_light);
mBtnCreateFolder.setImageResource(R.drawable.ic_action_create_light);
}
}
/**
* Calculates the Toolbar height in pixels.
*/
static int calculateToolbarSize(Context context) {
if (context == null) {
return 0;
}
Resources.Theme curTheme = context.getTheme();
if (curTheme == null) {
return 0;
}
TypedArray att = curTheme.obtainStyledAttributes(RES_IDS_ACTION_BAR_SIZE);
if (att == null) {
return 0;
}
float size = att.getDimension(0, 0);
att.recycle();
return (int) size;
}
/** Returns the value of the desired theme integer attribute, or -1 if not found **/
static int themeIntAttr(Context context, String attr) {
final Resources.Theme theme = context.getTheme();
if (theme == null) {
return -1;
}
final TypedValue value = new TypedValue();
final int id = context.getResources().getIdentifier(attr, "attr", context.getPackageName());
if (id == 0) {
// Not found
return -1;
}
theme.resolveAttribute(id, value, true);
return value.data;
}
@SuppressWarnings("deprecation")
private void init() {
setSubmitOnClick(true);
Resources.Theme theme = getContext().getTheme();
TypedValue hintColor = new TypedValue();
TypedValue suggestionColor = new TypedValue();
theme.resolveAttribute(android.R.attr.textColorSecondary, hintColor, true);
theme.resolveAttribute(android.R.attr.textColorSecondaryInverse, suggestionColor, true);
setHintTextColor(hintColor.data);
((ImageView) findViewById(com.miguelcatalan.materialsearchview.R.id.action_up_btn))
.setColorFilter(suggestionColor.data, PorterDuff.Mode.SRC_IN);
if (suggestionIcon != null) {
suggestionIcon.setColorFilter(suggestionColor.data, PorterDuff.Mode.SRC_IN);
setSuggestionIcon(suggestionIcon);
}
if (closeIcon != null) {
closeIcon.setColorFilter(hintColor.data, PorterDuff.Mode.SRC_IN);
setCloseIcon(closeIcon);
}
}
@TargetApi(Build.VERSION_CODES.LOLLIPOP)
@Override
public void inflate(Resources resources, XmlPullParser parser, AttributeSet attrs,
Resources.Theme theme)
throws XmlPullParserException, IOException {
super.inflate(resources, parser, attrs, theme);
final TypedArray custom = DrawableHelper.obtainAttributes(resources, theme, attrs,
R.styleable.GridDrawable);
mRowCount = custom.getInt(R.styleable.GridDrawable_android_rowCount, 1);
mColumnCount = custom.getInt(R.styleable.GridDrawable_android_columnCount, 1);
mHorizontalSpacing = custom.getDimension(R.styleable.GridDrawable_android_horizontalSpacing,
0);
mVerticalSpacing = custom.getDimension(R.styleable.GridDrawable_android_verticalSpacing,
0);
mConstantSize = custom.getBoolean(R.styleable.GridDrawable_android_constantSize,
false);
custom.recycle();
setWrappedDrawableFormText(resources, parser, attrs, theme);
}
public void setCommentStateUnhighlighted(final CommentViewHolder holder,
final CommentNode baseNode, boolean animate) {
if (animate) {
collapseAndRemove(holder.menuArea);
} else {
resetMenu(holder.menuArea, true);
}
int color;
Comment c = baseNode.getComment();
if (lastSeen != 0
&& lastSeen < c.getCreated().getTime()
&& !dataSet.single
&& SettingValues.commentLastVisit
&& !Authentication.name.equals(c.getAuthor())) {
color = Palette.getColor(baseNode.getComment().getSubredditName());
color = Color.argb(20, Color.red(color), Color.green(color), Color.blue(color));
} else {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = mContext.getTheme();
theme.resolveAttribute(R.attr.card_background, typedValue, true);
color = typedValue.data;
}
int dwidth = (int) (3 * Resources.getSystem().getDisplayMetrics().density);
int width = 0;
//Padding on the left, starting with the third comment
for (int i = 2; i < baseNode.getDepth(); i++) {
width += dwidth;
}
RecyclerView.LayoutParams params =
(RecyclerView.LayoutParams) holder.itemView.getLayoutParams();
params.setMargins(width, 0, 0, 0);
holder.itemView.setLayoutParams(params);
holder.itemView.findViewById(R.id.background).setBackgroundColor(color);
}
private static int getBorderColor(Context context) {
Resources.Theme theme = context.getTheme();
TypedValue typedValue = new TypedValue();
if (theme.resolveAttribute(R.attr.colorPrimary, typedValue, true)) {
return typedValue.data;
}
return Color.TRANSPARENT;
}
private void tint(Context ctx) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = ctx.getTheme();
theme.resolveAttribute(android.R.attr.textColorPrimary, typedValue, true);
TypedArray arr =
ctx.obtainStyledAttributes(typedValue.data, new int[]{
android.R.attr.textColorSecondary});
int secondaryColor = arr.getColor(0, -1);
setColorFilter(secondaryColor, PorterDuff.Mode.SRC_IN);
arr.recycle();
}
@Override
public void inflate(
@NonNull final Resources r,
@NonNull final XmlPullParser parser,
@NonNull final AttributeSet attrs,
@Nullable final Resources.Theme theme) throws XmlPullParserException, IOException {
super.inflate(r, parser, attrs, theme);
sceneConfigurator.configureSceneFromAttributes(scene, r, attrs);
}
private void construct(Context context, AttributeSet attrs) {
mHandler = new Handler();
setDrawingCacheEnabled(true);
setLayerType(LAYER_TYPE_SOFTWARE, null); //Only works for software layers
mPaint = createPaint(false);
Resources.Theme theme = context.getTheme();
if (theme != null) {
TypedArray a = theme.obtainStyledAttributes(
attrs,
R.styleable.MaskableLayout,
0, 0);
try {
//Load the mask if specified in xml
initMask(loadMask(a));
//Load the mode if specified in xml
mPorterDuffXferMode = getModeFromInteger(
a.getInteger(R.styleable.MaskableLayout_porterduffxfermode, 0));
initMask(mDrawableMask);
//Check antiAlias
if (a.getBoolean(R.styleable.MaskableLayout_anti_aliasing, false)) {
//Recreate paint with anti aliasing enabled
//This can take a performance hit.
mPaint = createPaint(true);
}
} finally {
if (a != null) {
a.recycle();
}
}
} else {
log("Couldn't load theme, mask in xml won't be loaded.");
}
registerMeasure();
}
public StandardShowcaseDrawer(Resources resources, Resources.Theme theme) {
PorterDuffXfermode xfermode = new PorterDuffXfermode(PorterDuff.Mode.MULTIPLY);
eraserPaint = new Paint();
eraserPaint.setColor(0xFFFFFF);
eraserPaint.setAlpha(0);
eraserPaint.setXfermode(xfermode);
eraserPaint.setAntiAlias(true);
basicPaint = new Paint();
showcaseRadius = resources.getDimension(com.github.amlcurran.showcaseview.R.dimen.showcase_radius);
showcaseDrawable = ResourcesCompat.getDrawable(resources, com.github.amlcurran.showcaseview.R.drawable.cling_bleached, theme);
}
/**
* Returns a color from an attribute reference.
*
* @param context Pass the activity context, not the application context
* @param attr The attribute reference to be resolved
*
* @return int array of color value
*/
@ColorInt
public static int getColorFromAttr(Context context, @AttrRes int attr) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = context.getTheme();
theme.resolveAttribute(attr, typedValue, true);
return typedValue.data;
}
/**
* error with index
*
* @param display
* @param result
*/
private void onError(final String display, final String result) {
final int indexError = display.indexOf(LogicEvaluator.ERROR_INDEX_STRING);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
TypedValue typedValue = new TypedValue();
Resources.Theme theme = this.getTheme();
theme.resolveAttribute(R.attr.colorResultError, typedValue, true);
int color = typedValue.data;
animateRipple(mDisplayForeground, mCurrentButton, color, new AnimationFinishedListener() {
@Override
public void onAnimationFinished() {
mInputDisplay.setText((display));
if (indexError >= 0) {
mInputDisplay.setSelection(indexError, indexError + 1);
}
setState(CalculatorState.ERROR);
setTextError(result);
}
}, true);
} else {
mInputDisplay.setText((display));
if (indexError >= 0) {
mInputDisplay.setSelection(indexError, indexError + 1);
}
setState(CalculatorState.ERROR);
setTextError(result);
}
}
private void applyCustomProperty(AttributeSet attrs) {
mPhoneUtil = PhoneNumberUtil.createInstance(getContext());
Resources.Theme theme = getContext().getTheme();
TypedArray a = theme.obtainStyledAttributes(attrs, R.styleable.CountryCodePicker, 0, 0);
try {
mHidePhoneCode = a.getBoolean(R.styleable.CountryCodePicker_ccp_hidePhoneCode, false);
mShowFullName = a.getBoolean(R.styleable.CountryCodePicker_ccp_showFullName, false);
mHideNameCode = a.getBoolean(R.styleable.CountryCodePicker_ccp_hideNameCode, false);
mIsHintEnabled = a.getBoolean(R.styleable.CountryCodePicker_ccp_enableHint, true);
// enable auto formatter for phone number input
mIsEnablePhoneNumberWatcher =
a.getBoolean(R.styleable.CountryCodePicker_ccp_enablePhoneAutoFormatter, true);
setKeyboardAutoPopOnSearch(
a.getBoolean(R.styleable.CountryCodePicker_ccp_keyboardAutoPopOnSearch, true));
mCustomMasterCountries = a.getString(R.styleable.CountryCodePicker_ccp_customMasterCountries);
refreshCustomMasterList();
mCountryPreference = a.getString(R.styleable.CountryCodePicker_ccp_countryPreference);
refreshPreferredCountries();
applyCustomPropertyOfDefaultCountryNameCode(a);
showFlag(a.getBoolean(R.styleable.CountryCodePicker_ccp_showFlag, true));
applyCustomPropertyOfColor(a);
// text font
String fontPath = a.getString(R.styleable.CountryCodePicker_ccp_textFont);
if (fontPath != null && !fontPath.isEmpty()) setTypeFace(fontPath);
//text size
int textSize = a.getDimensionPixelSize(R.styleable.CountryCodePicker_ccp_textSize, 0);
if (textSize > 0) {
mTvSelectedCountry.setTextSize(TypedValue.COMPLEX_UNIT_PX, textSize);
setFlagSize(textSize);
setArrowSize(textSize);
} else { //no text size specified
DisplayMetrics dm = getContext().getResources().getDisplayMetrics();
int defaultSize = Math.round(18 * (dm.xdpi / DisplayMetrics.DENSITY_DEFAULT));
setTextSize(defaultSize);
}
//if arrow arrow size is explicitly defined
int arrowSize = a.getDimensionPixelSize(R.styleable.CountryCodePicker_ccp_arrowSize, 0);
if (arrowSize > 0) setArrowSize(arrowSize);
mSelectionDialogShowSearch =
a.getBoolean(R.styleable.CountryCodePicker_ccp_selectionDialogShowSearch, true);
setClickable(a.getBoolean(R.styleable.CountryCodePicker_ccp_clickable, true));
mSetCountryByTimeZone =
a.getBoolean(R.styleable.CountryCodePicker_ccp_setCountryByTimeZone, true);
// Set to default phone code if no country name code set in attribute.
if (mDefaultCountryNameCode == null || mDefaultCountryNameCode.isEmpty()) {
setDefaultCountryFlagAndCode();
}
} catch (Exception e) {
Log.d(TAG, "exception = " + e.toString());
if (isInEditMode()) {
mTvSelectedCountry.setText(
getContext().getString(R.string.phone_code,
getContext().getString(R.string.country_indonesia_number)));
} else {
mTvSelectedCountry.setText(e.getMessage());
}
} finally {
a.recycle();
}
}
private void bindComplexComment(ComplexComment comment) {
final ComplexComment complexComment = comment;
final FragmentActivity context = getContext();
final Resources.Theme theme = context.getTheme();
TypedValue primaryBackground = new TypedValue();
TypedValue secondaryBackground = new TypedValue();
theme.resolveAttribute(R.attr.widgetBackgroundColorPrimary, primaryBackground, true);
theme.resolveAttribute(R.attr.widgetBackgroundColorSecondary, secondaryBackground, true);
// switch background color according to level
int bgColor = (complexComment.getLevel() == 1) ? primaryBackground.resourceId
: secondaryBackground.resourceId;
int color;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
color = context.getColor(bgColor);
} else {
color = context.getResources()
.getColor(bgColor);
}
outerLayout.setBackgroundColor(color);
// set left/start margin width in default comment
setLayoutLeftPadding(complexComment);
if (complexComment.getLevel() == 1) {
// first level
replyLayout.setVisibility(View.VISIBLE);
compositeSubscription.add(RxView.clicks(replyLayout)
.flatMap(aVoid -> complexComment.observeReplySubmission()
.doOnError(err -> {
Snackbar.make(userAvatar, R.string.error_occured, Snackbar.LENGTH_SHORT);
})
.toObservable())
.retry()
.subscribe(aVoid -> { /* nothing else to do */ }, err -> {
CrashReport.getInstance()
.log(err);
}));
} else {
// other levels
replyLayout.setVisibility(View.GONE);
userAvatar.setScaleX(0.7F);
userAvatar.setScaleY(0.7F);
}
}
public static int getThemeResId(Context context, int attr) {
Resources.Theme theme = context.getTheme();
TypedValue typedValueAttr = new TypedValue();
theme.resolveAttribute(attr, typedValueAttr, true);
return typedValueAttr.resourceId;
}
@SuppressLint("NewApi")
public static int loadTextureFromResource(final Context context, final int resId, final Resources.Theme theme) {
if (DEBUG) Log.v(TAG, "loadTextureFromResource:");
// Create an empty, mutable bitmap
final Bitmap bitmap = Bitmap.createBitmap(256, 256, Bitmap.Config.ARGB_8888);
// get a canvas to paint over the bitmap
final Canvas canvas = new Canvas(bitmap);
canvas.drawARGB(0,0,255,0);
// get a background image from resources
// note the image format must match the bitmap format
final Drawable background;
if (BuildCheck.isAndroid5()) {
background = context.getResources().getDrawable(resId, theme);
} else {
background = context.getResources().getDrawable(resId);
}
background.setBounds(0, 0, 256, 256);
background.draw(canvas); // draw the background to our bitmap
final int[] textures = new int[1];
//Generate one texture pointer...
GLES30.glGenTextures(1, textures, 0);
//...and makeCurrent it to our array
GLES30.glBindTexture(GLES30.GL_TEXTURE_2D, textures[0]);
//Create Nearest Filtered Texture
GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D,
GLES30.GL_TEXTURE_MIN_FILTER, GLES30.GL_NEAREST);
GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D,
GLES30.GL_TEXTURE_MAG_FILTER, GLES30.GL_LINEAR);
//Different possible texture parameters, e.g. GLES30.GL_CLAMP_TO_EDGE
GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D,
GLES30.GL_TEXTURE_WRAP_S, GLES30.GL_REPEAT);
GLES30.glTexParameterf(GLES30.GL_TEXTURE_2D,
GLES30.GL_TEXTURE_WRAP_T, GLES30.GL_REPEAT);
//Use the Android GLUtils to specify a two-dimensional texture image from our bitmap
GLUtils.texImage2D(GLES30.GL_TEXTURE_2D, 0, bitmap, 0);
//Clean up
bitmap.recycle();
return textures[0];
}
/**
* Creates a new context wrapper with the specified theme.
* <p>
* Unlike {@link #SceneContextThemeWrapper(Context, int)}, the theme passed to
* this constructor will completely replace the base context's theme.
*
* @param base the base context
* @param theme the theme against which resources should be inflated
*/
public SceneContextThemeWrapper(@NonNull Context base, @NonNull Resources.Theme theme) {
super(base);
mTheme = Utility.requireNonNull(theme, "theme can't be null");
mIsThemeFromActivity = true;
}
protected void onApplyThemeResource(Resources.Theme theme, int resid, boolean first) {
}
void applyTheme(Drawable drawable, Resources.Theme t);