Android 手机横竖屏切换

竖屏与横批切换

手机有竖屏与横屏两种模式,两种屏幕方向不但造成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 属性可以设置只能为竖屏或横屏

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值