Android Studio 屏幕方向以及UI界面状态的保存

Posted 专注WEB开发技术 @ 修身、齐家、治国、平天下!

tags:

篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Android Studio 屏幕方向以及UI界面状态的保存相关的知识,希望对你有一定的参考价值。

package com.example.orientation;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

import androidx.appcompat.app.AppCompatActivity;

public class MainActivity extends AppCompatActivity {
/*
    = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
    本实例主要学习,屏幕翻转时,界面如何自适应,创建横屏布局
    1.禁止切换横屏:在 AndroidManifest.xml-->application->activity->中设置如下代码(android:screenOrientation="portrait")
      <activity android:name=".MainActivity" android:screenOrientation="portrait" >
    2. 创建 Landscape 布局,横屏时,会自动加载 Landscape 的布局界面(清单文件中,注意去掉 android:screenOrientation="portrait" )
    3. 翻转屏幕时,保存窗口控件的状态值;

    = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = = =
 */
    Button button;
    TextView textView;

    String TAG = "myTag";

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        button  = findViewById(R.id.button );
        textView = findViewById(R.id.textView);

        //如果State中的值不为空,如果有相应的这个组件的值,则读取出来赋值上去
        if(savedInstanceState !=null)
        {
            String s = savedInstanceState.getString("key");
            textView.setText(s);
        }

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                textView.setText(button.getText());
            }
        });
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        Log.d(TAG,"onDestroy:");
    }

    @Override
    //将 textView 中的值,先保存到 outState 中(键值对)
    public void onSaveInstanceState(Bundle outState) {
        super.onSaveInstanceState(outState);
        outState.putString("key",textView.getText().toString());
    }
}

  项目:Orientation

以上是关于Android Studio 屏幕方向以及UI界面状态的保存的主要内容,如果未能解决你的问题,请参考以下文章

Android Studio学习随笔-UI线程阻塞以及优化

如何一次将屏幕方向应用于纵向所有布局 android studio

升级到 Android Studio 2.0 后,我无法在 Android 模拟器中更改屏幕方向

android--屏幕旋转方法总结

android studio 做ui界面都是用手工敲代码吗?

iOS、Android 开发单位换算及 UI 切图要求