下面列出了怎么用android.content.res.Configuration的API类实例代码及写法,或者点击链接到github查看源代码。
public void initialize(YoukuBasePlayerActivity mYoukuBaseActivity){
PackageManager pm = mYoukuBaseActivity.getPackageManager();
String ver = "4.1";
try {
ver = pm.getPackageInfo(mYoukuBaseActivity.getPackageName(), 0).versionName;
} catch (NameNotFoundException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
boolean isTablet = (this.getResources().getConfiguration().screenLayout & Configuration.SCREENLAYOUT_SIZE_MASK) >= Configuration.SCREENLAYOUT_SIZE_LARGE;
String ua = (isTablet ? "Youku HD;" : "Youku;") + ver
+ ";Android;" + android.os.Build.VERSION.RELEASE + ";"
+ android.os.Build.MODEL;
Logger.d(TAG,"initialize(): ua = " + ua);
initialize(mYoukuBaseActivity, 10001, "4e308edfc33936d7", ver, ua, false,-7L,"631l1i1x3fv5vs2dxlj5v8x81jqfs2om");
}
public void setAndRefreshLanguage(){
// 获得res资源对象
Resources resources = getResources();
// 获得屏幕参数:主要是分辨率,像素等。
DisplayMetrics metrics = resources.getDisplayMetrics();
// 获得配置对象
Configuration config = resources.getConfiguration();
//区别17版本(其实在17以上版本通过 config.locale设置也是有效的,不知道为什么还要区别)
//在这里设置需要转换成的语言,也就是选择用哪个values目录下的strings.xml文件
int value= SPUtil.getGlobalSharedPreferences(this).getInt(Constants.PREFERENCE_LANGUAGE,Constants.PREFERENCE_LANGUAGE_DEFAULT);
Locale locale=null;
switch (value){
default:break;
case Constants.LANGUAGE_FOLLOW_SYSTEM:locale=Locale.getDefault();break;
case Constants.LANGUAGE_CHINESE:locale=Locale.SIMPLIFIED_CHINESE;break;
case Constants.LANGUAGE_ENGLISH:locale=Locale.ENGLISH;break;
}
if(locale==null)return;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN_MR1) {
config.setLocale(locale);
} else {
config.locale =locale;
}
resources.updateConfiguration(config, metrics);
}
private int getCurrentOrientation() {
int rotation = getWindowManager().getDefaultDisplay().getRotation();
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
switch (rotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_90:
return ActivityInfo.SCREEN_ORIENTATION_LANDSCAPE;
default:
return ActivityInfo.SCREEN_ORIENTATION_REVERSE_LANDSCAPE;
}
} else {
switch (rotation) {
case Surface.ROTATION_0:
case Surface.ROTATION_270:
return ActivityInfo.SCREEN_ORIENTATION_PORTRAIT;
default:
return ActivityInfo.SCREEN_ORIENTATION_REVERSE_PORTRAIT;
}
}
}
@Override
public void onListItemClick(ListView l, View v, int position, long id) {
String videoId = VIDEO_LIST.get(position).videoId;
VideoFragment videoFragment =
(VideoFragment) getFragmentManager().findFragmentById(R.id.video_fragment_container);
videoFragment.setVideoId(videoId);
// The videoBox is INVISIBLE if no video was previously selected, so we need to show it now.
if (videoBox.getVisibility() != View.VISIBLE) {
if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// Initially translate off the screen so that it can be animated in from below.
videoBox.setTranslationY(videoBox.getHeight());
}
videoBox.setVisibility(View.VISIBLE);
}
// If the fragment is off the screen, we animate it in.
if (videoBox.getTranslationY() > 0) {
videoBox.animate().translationY(0).setDuration(ANIMATION_DURATION_MILLIS);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig)
{
super.onConfigurationChanged(newConfig);
if (!onlySelect && floatingButton != null)
{
floatingButton.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener()
{
@Override
public void onGlobalLayout()
{
floatingButton.setTranslationY(floatingHidden ? (!FeaturedSettings.tabSettings.hideTabs && FeaturedSettings.tabSettings.tabsToBottom) ? AndroidUtilities.dp(150) : AndroidUtilities.dp(100) : 0);
unreadFloatingButtonContainer.setTranslationY(floatingHidden ? AndroidUtilities.dp(74) : 0);
floatingButton.setClickable(!floatingHidden);
if (floatingButton != null)
{
floatingButton.getViewTreeObserver().removeOnGlobalLayoutListener(this);
}
}
});
}
}
private boolean getAnimation(String tag) {
for (String immovableClass : G.generalImmovableClasses) {
if (tag.equals(immovableClass)) {
return false;
}
}
if (G.twoPaneMode) {
if ((G.context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) && (tag.equals(FragmentChat.class.getName()))) {
return true;
}
if (G.iTowPanModDesinLayout != null && G.iTowPanModDesinLayout.getBackChatVisibility()) {
return true;
}
return false;
} else {
return true;
}
}
public static int getUsefulScreenWidth(Context context, boolean hasNotch) {
int result = getRealScreenSize(context)[0];
int orientation = context.getResources().getConfiguration().orientation;
boolean isLandscape = orientation == Configuration.ORIENTATION_LANDSCAPE;
if (!hasNotch) {
if (isLandscape && DeviceHelper.isEssentialPhone()
&& Build.VERSION.SDK_INT < Build.VERSION_CODES.O) {
// https://arstechnica.com/gadgets/2017/09/essential-phone-review-impressive-for-a-new-company-but-not-competitive/
// 这里说挖孔屏是状态栏高度的两倍, 但横屏好像小了一点点
result -= 2 * StatusBarHelper.getStatusbarHeight(context);
}
return result;
}
if (isLandscape) {
// 华为挖孔屏横屏时,会把整个 window 往后移动,因此,可用区域减小
if (DeviceHelper.isHuawei() && !DisplayHelper.huaweiIsNotchSetToShowInSetting(context)) {
result -= NotchHelper.getNotchSizeInHuawei(context)[1];
}
// TODO vivo 设置-系统导航-导航手势样式-显示手势操作区域 打开的情况下,应该减去手势操作区域的高度,但无API
// TODO vivo 设置-显示与亮度-第三方应用显示比例 选为安全区域显示时,整个 window 会移动,应该减去移动区域,但无API
// TODO oppo 设置-显示与亮度-应用全屏显示-凹形区域显示控制 关闭是,整个 window 会移动,应该减去移动区域,但无API
}
return result;
}
void updateFromConfiguration(Context context, Resources resources, int wPx, int hPx,
int awPx, int ahPx) {
Configuration configuration = resources.getConfiguration();
isLandscape = (configuration.orientation == Configuration.ORIENTATION_LANDSCAPE);
isTablet = resources.getBoolean(R.bool.is_tablet);
isLargeTablet = resources.getBoolean(R.bool.is_large_tablet);
if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.JELLY_BEAN_MR1) {
isLayoutRtl = (configuration.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL);
} else {
isLayoutRtl = false;
}
widthPx = wPx;
heightPx = hPx;
availableWidthPx = awPx;
availableHeightPx = ahPx;
updateAvailableDimensions(context);
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {// 横屏
// Log.e(TAG, "onConfigurationChanged: " + "横屏");
onConfigurationLandScape();
} else if (this.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
// Log.e(TAG, "onConfigurationChanged: " + "竖屏");
onConfigurationPortrait();
}
}
private void refreshKeyboard() {
//Set the Init
boolean small = true;
if (mCurrentOrientation == Configuration.ORIENTATION_PORTRAIT) {
if (mKeyboardPortraitType == 0) {
mKeyboards.setKeyboardType(KeyboardSwitcher.KEYBOARD_NORM);
} else {
mKeyboards.setKeyboardType(KeyboardSwitcher.KEYBOARD_LARGE);
small = false;
}
//Set Size
mKeyboards.setKeyboardSize(mKeyboardPortraitHeight);
} else {
if (mKeyboardLandscapeType == 0) {
mKeyboards.setKeyboardType(KeyboardSwitcher.KEYBOARD_NORM);
} else {
mKeyboards.setKeyboardType(KeyboardSwitcher.KEYBOARD_LARGE);
small = false;
}
//Set Size
mKeyboards.setKeyboardSize(mKeyboardLandscapeHeight);
}
if (mInputView != null) {
mInputView.setKeyboard(mKeyboards.getCurrentKeyboard());
if (small) {
mInputView.setMode(LatinKeyboardView.MODE_SMALL);
} else {
mInputView.setMode(LatinKeyboardView.MODE_LARGE);
}
// Log.v("SpartacusRex", "New Keyboard.. Setting Positions..");
// mInputView.setKeyPositions();
}
}
private void setUpManualResourceQualifiers(View view) {
final Configuration configuration = getResources().getConfiguration();
String mccAndMnc = getString(R.string.fallback_no_qualifier);
if (configuration.mcc != 0) { // NOTE: According to the docs, 0 if undefined, even though Wikipedia says 0 is used for test networks
mccAndMnc = "mcc" + String.format(Locale.US, "%03d", configuration.mcc); // Mobile country codes should always be 3 decimals, but can be prefixed with 0
mccAndMnc += "-mnc" + getBestGuessMobileNetworkCode(configuration);
}
((TextView) view.findViewById(R.id.textView_mcc_and_mnc)).setText(mccAndMnc);
((TextView) view.findViewById(R.id.textView_locale)).setText(configuration.locale.getLanguage() + "-r" + configuration.locale.getCountry());
String smallestWidth = getString(R.string.fallback_no_qualifier);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
if (configuration.smallestScreenWidthDp != Configuration.SMALLEST_SCREEN_WIDTH_DP_UNDEFINED) {
smallestWidth = "sw" + configuration.smallestScreenWidthDp + "dp";
}
}
((TextView) view.findViewById(R.id.textView_smallest_width)).setText(smallestWidth);
String availableWidth = getString(R.string.fallback_no_qualifier);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
if (configuration.screenWidthDp != Configuration.SCREEN_WIDTH_DP_UNDEFINED) {
availableWidth = "w" + configuration.screenWidthDp + "dp";
}
}
((TextView) view.findViewById(R.id.textView_available_width)).setText(availableWidth);
String availableHeight = getString(R.string.fallback_no_qualifier);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB_MR2) {
if (configuration.screenHeightDp != Configuration.SCREEN_HEIGHT_DP_UNDEFINED) {
availableHeight = "h" + configuration.screenHeightDp + "dp";
}
}
((TextView) view.findViewById(R.id.textView_available_height)).setText(availableHeight);
}
public static void setLocale(Context base, String language) {
Locale locale = new Locale(language);
Locale.setDefault(locale);
Configuration config = new Configuration();
config.locale = locale;
base.getResources().updateConfiguration(config,
base.getResources().getDisplayMetrics());
}
@TargetApi(Build.VERSION_CODES.N)
private static Context updateResources(Context context) {
Resources resources = context.getResources();
Locale locale = getLocaleByLanguage(context);
Configuration configuration = resources.getConfiguration();
configuration.setLocale(locale);
configuration.setLocales(new LocaleList(locale));
return context.createConfigurationContext(configuration);
}
@SuppressWarnings({"UnusedDeclaration", "UnusedAssignment"})
private void setOrientationProperties(ArrayList<Pair<String, String>> parameters) {
boolean allow_orientation_change = true;
AdActivity.OrientationEnum orientation = AdActivity.OrientationEnum.none;
for (Pair<String, String> bnvp : parameters) {
if (bnvp.first.equals("allow_orientation_change")) {
allow_orientation_change = Boolean.parseBoolean(bnvp.second);
} else if (bnvp.first.equals("force_orientation")) {
orientation = parseForceOrientation(bnvp.second);
}
}
// orientationProperties only affects expanded state
if (expanded || owner.adView.isInterstitial()) {
Activity containerActivity = owner.isFullScreen
? getFullscreenActivity() : (Activity) owner.getContextFromMutableContext();
if (allow_orientation_change) {
AdActivity.unlockOrientation(containerActivity);
} else {
int androidOrientation = Configuration.ORIENTATION_UNDEFINED;
switch (orientation) {
case landscape:
androidOrientation = Configuration.ORIENTATION_LANDSCAPE;
break;
case portrait:
androidOrientation = Configuration.ORIENTATION_PORTRAIT;
break;
case none:
default:
break;
}
AdActivity.lockToConfigOrientation(containerActivity, androidOrientation);
}
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
//如果旋转了就全屏
if (isPlay && !isPause) {
detailPlayer.onConfigurationChanged(this, newConfig, orientationUtils, true, true);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mDelegate != null) {
mDelegate.onConfigurationChanged(newConfig);
}
}
@Override
public void onConfigurationChanged(Configuration newConfig) {
super.onConfigurationChanged(newConfig);
if (mDrawerToggle != null) {
mDrawerToggle.onConfigurationChanged(newConfig);
}
}
@Override
public void onConfigurationChanged(Configuration newParentConfig) {
final int prevWinMode = getWindowingMode();
super.onConfigurationChanged(newParentConfig);
final int winMode = getWindowingMode();
if (prevWinMode == winMode) {
return;
}
if (prevWinMode != WINDOWING_MODE_UNDEFINED && winMode == WINDOWING_MODE_PINNED) {
// Entering PiP from fullscreen, reset the snap fraction
mDisplayContent.mPinnedStackControllerLocked.resetReentrySnapFraction(this);
} else if (prevWinMode == WINDOWING_MODE_PINNED && winMode != WINDOWING_MODE_UNDEFINED
&& !isHidden()) {
// Leaving PiP to fullscreen, save the snap fraction based on the pre-animation bounds
// for the next re-entry into PiP (assuming the activity is not hidden or destroyed)
final TaskStack pinnedStack = mDisplayContent.getPinnedStack();
if (pinnedStack != null) {
final Rect stackBounds;
if (pinnedStack.lastAnimatingBoundsWasToFullscreen()) {
// We are animating the bounds, use the pre-animation bounds to save the snap
// fraction
stackBounds = pinnedStack.mPreAnimationBounds;
} else {
// We skip the animation if the fullscreen configuration is not compatible, so
// use the current bounds to calculate the saved snap fraction instead
// (see PinnedActivityStack.skipResizeAnimation())
stackBounds = mTmpRect;
pinnedStack.getBounds(stackBounds);
}
mDisplayContent.mPinnedStackControllerLocked.saveReentrySnapFraction(this,
stackBounds);
}
}
}
/**
* 判断是否竖屏
* @param context {@link Context}
* @return {@code true} yes, {@code false} no
*/
public static boolean isPortrait(final Context context) {
try {
return context.getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
} catch (Exception e) {
LogPrintUtils.eTag(TAG, e, "isPortrait");
}
return false;
}
@Override
protected void onResume() {
super.onResume();
View headerView = navigationView.getHeaderView(0);
try {
final ImageView avatarImageView = headerView.findViewById(R.id.avatar_image_view);
User user = UserHelper.getInstance(getApplicationContext()).readCurrentUser();
GlideApp.with(this)
.load(Avatar.Companion.forUser(user))
.circleCrop()
.fallback(R.drawable.ic_account_circle_white_48dp)
.error(R.drawable.ic_account_circle_white_48dp)
.into(avatarImageView);
TextView displayName = headerView.findViewById(R.id.display_name);
displayName.setText(user.getDisplayName());
TextView email = headerView.findViewById(R.id.email);
email.setText(user.getEmail());
email.setVisibility(StringUtils.isNoneBlank(user.getEmail()) ? View.VISIBLE : View.GONE);
} catch (UserException e) {
Log.e(LOG_NAME, "Error pulling current user from the database", e);
}
// This activity is 'singleTop' and as such will not recreate itself based on a uiMode configuration change.
// Force this by check if the uiMode has changed.
int nightMode = getResources().getConfiguration().uiMode & Configuration.UI_MODE_NIGHT_MASK;
if (nightMode != currentNightMode) {
recreate();
}
if (shouldReportLocation() && locationPermissionGranted != (ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED)) {
locationPermissionGranted = ContextCompat.checkSelfPermission(getApplicationContext(), Manifest.permission.ACCESS_FINE_LOCATION) == PackageManager.PERMISSION_GRANTED;
// User allowed location service permission in settings, start location services.
application.startLocationService();
}
}
@Override
public Resources getResources() {
Resources res = super.getResources();
if (res.getConfiguration().fontScale != 1) {//非默认值
Configuration newConfig = new Configuration();
newConfig.setToDefaults();//设置默认
res.updateConfiguration(newConfig, res.getDisplayMetrics());
}
return res;
}
/** 展示编辑界面*/
protected void showEditPage(Context context, Platform platform, ShareParams sp) {
com.sharesdk.onekeyshare.themes.classic.EditPage page;
int orientation = context.getResources().getConfiguration().orientation;
if (orientation == Configuration.ORIENTATION_PORTRAIT) {
page = new EditPagePort(this);
} else {
page = new EditPageLand(this);
}
page.setPlatform(platform);
page.setShareParams(sp);
page.show(context, null);
}
@Override
public void onConfigurationChanged (Configuration newConfig) {
WindowManager wm = (WindowManager) this.context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
Point dSize = new Point();
display.getSize(dSize);
this.sl1.displayWidth = this.sl2.displayWidth = this.sl3.displayWidth = dSize.x - iconSize - 5;
this.invalidate();
}
/**
* 配置变更
*
* @param newConfig 新配置
*/
public void onConfigurationChanged(@NonNull Configuration newConfig) {
if (mItems.isEmpty())
return;
for (ViewHolder holder : mItems) {
if (!mItemsInLayout.contains(holder))
holder.itemView.dispatchConfigurationChanged(newConfig);
}
}
@Override
public void onPictureInPictureModeChanged (boolean isInPictureInPictureMode, Configuration newConfig) {
if (isInPictureInPictureMode) {
// Hide the full-screen UI (controls, etc.) while in picture-in-picture mode.
findViewById(R.id.buttonBar).setVisibility(View.GONE);
} else {
// Restore the full-screen UI.
findViewById(R.id.buttonBar).setVisibility(View.VISIBLE);
}
}
@Override
protected void onResume() {
super.onResume();
int orientation = Resources.getSystem().getConfiguration().orientation;
presenter.getProgramStages(programId, enrollmentId); //TODO: enrollment / event path
int columnCount = (orientation == Configuration.ORIENTATION_LANDSCAPE) ? 3 : 2;
binding.recyclerView.setLayoutManager(new GridLayoutManager(this, columnCount));
}
/**
* Returns whether the app is running on a TV device.
*
* @param context Any context.
* @return Whether the app is running on a TV device.
*/
public static boolean isTv(Context context) {
// See https://developer.android.com/training/tv/start/hardware.html#runtime-check.
UiModeManager uiModeManager =
(UiModeManager) context.getApplicationContext().getSystemService(UI_MODE_SERVICE);
return uiModeManager != null
&& uiModeManager.getCurrentModeType() == Configuration.UI_MODE_TYPE_TELEVISION;
}
private SystemBarConfig(Activity activity, boolean translucentStatusBar, boolean traslucentNavBar) {
Resources res = activity.getResources();
mInPortrait = (res.getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT);
mSmallestWidthDp = getSmallestWidthDp(activity);
mStatusBarHeight = getInternalDimensionSize(res, STATUS_BAR_HEIGHT_RES_NAME);
mActionBarHeight = getActionBarHeight(activity);
mNavigationBarHeight = getNavigationBarHeight(activity);
mNavigationBarWidth = getNavigationBarWidth(activity);
mHasNavigationBar = (mNavigationBarHeight > 0);
mTranslucentStatusBar = translucentStatusBar;
mTranslucentNavBar = traslucentNavBar;
}
@TargetApi(Build.VERSION_CODES.JELLY_BEAN_MR1)
private boolean isRTL() {
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN_MR1) {
return false;
}
Configuration config = getResources().getConfiguration();
return config.getLayoutDirection() == View.LAYOUT_DIRECTION_RTL;
}
@Test
public void testPortraitTablet() {
when(resources.getBoolean(R.bool.tablet)).thenReturn(true);
configuration.orientation = Configuration.ORIENTATION_PORTRAIT;
assertEquals(PORTRAIT_TABLET, brickSize.getSpans(context));
}