赞
踩
手机有竖屏与横屏两种模式,两种屏幕方向不但造成App界面的展示差异,而且竖屏和横屏切换之际,甚至会打乱App的生命周期。
为了避免横竖屏切换时重新加载界面的情况,Android设计了一种配置变更机制,在指定的环境配置发生变更之时,无需重启活动页面,只需执行特定的变更行为。该机制的实现过程分为两步:
修改AndroidManifest.xml,给activity节点增加 android:configChanges 属性
修改活动页面的Java代码,重写活动的 onConfigurationChanged 方法,补充对应的代码处理逻辑。
效果图
横屏时
代码
<?xml version="1.0" encoding="utf-8"?> <manifest xmlns:android="http://schemas.android.com/apk/res/android"> <application android:allowBackup="true" android:icon="@mipmap/ic_launcher" android:label="@string/app_name" android:roundIcon="@mipmap/ic_launcher_round" android:supportsRtl="true" android:theme="@style/Theme.AndroidAndroidDemo"> <activity android:name=".MainActivity" android:exported="true" android:configChanges="orientation|screenLayout|screenSize"> <intent-filter> <action android:name="android.intent.action.MAIN" /> <category android:name="android.intent.category.LAUNCHER" /> </intent-filter> <meta-data android:name="android.app.lib_name" android:value="" /> </activity> </application> </manifest>
package com.example.horizontalandportraitswitching; import androidx.annotation.NonNull; import androidx.appcompat.app.AppCompatActivity; import android.content.res.Configuration; import android.os.Bundle; import android.util.Log; import android.view.View; import android.widget.TextView; public class MainActivity extends AppCompatActivity { public TextView textView; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); textView = findViewById(R.id.mtext); Log.d("hu","activity创建了"); } //在配置项变更时出发.比如屏幕方向发生变更等等 @Override public void onConfigurationChanged(@NonNull Configuration newConfig) { super.onConfigurationChanged(newConfig); switch (newConfig.orientation){ case Configuration.ORIENTATION_PORTRAIT: textView.setText("当前屏幕为竖屏方向"); break; case Configuration.ORIENTATION_LANDSCAPE: textView.setText("当前屏幕为横屏方向"); break; default: break; } } }
注意:
修改AndroidManifest.xml,给activity节点增加 android:screenOrientation 属性可以设置只能为竖屏或横屏
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。