Android横竖屏切换configChanges="screenSize|orientation"避免activity销毁重建,Kotlin
如果不在Androidmanifest.xml设置activity的:
android:configChanges="screenSize|orientation"
那么,每次横竖屏切换activity都会重新走onCreate() ... onDestory()生命周期,即销毁重建。如果设置了上面的配置后,每次横竖屏切换,activity只是回调:
override fun onConfigurationChanged(newConfig: Configuration) {super.onConfigurationChanged(newConfig)}
而不再走或触发activity的创建-消耗重的生命周期。
import android.content.res.Configuration
import android.os.Bundle
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView
import androidx.appcompat.app.AppCompatActivity
import androidx.recyclerview.widget.GridLayoutManager
import androidx.recyclerview.widget.RecyclerView
import java.util.UUIDconst val ITEM_COUNT = 300class MainActivity : AppCompatActivity() {private var mAdapter: MyAdapter? = nulloverride fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)Log.d("fly", "onCreate")setContentView(R.layout.activity_main)val rv = findViewById<RecyclerView>(R.id.rv)val layoutManager = GridLayoutManager(this, 3)rv.layoutManager = layoutManagermAdapter = MyAdapter()rv.adapter = mAdapter}override fun onDestroy() {super.onDestroy()Log.d("fly", "onDestroy")}class MyAdapter : RecyclerView.Adapter<MyVH> {private var mList = mutableListOf<MyItem>()constructor() {val list = mutableListOf<MyItem>()for (i in 0 until ITEM_COUNT) {val item = MyItem(i)item.data = 0Litem.change = falselist.add(item)}mList = list}override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): MyVH {val view = LayoutInflater.from(parent.context).inflate(android.R.layout.simple_list_item_2, parent, false)return MyVH(view)}override fun getItemCount(): Int {return mList.size}override fun onBindViewHolder(holder: MyVH, position: Int) {holder.text1.text = "pos=${mList[position].pos}"holder.text2.text = "data=${mList[position].data}"}}class MyVH(itemView: View) : RecyclerView.ViewHolder(itemView) {val text1: TextView = itemView.findViewById(android.R.id.text1)val text2: TextView = itemView.findViewById(android.R.id.text2)}class MyItem {var pos = 0var data = 0Lvar contentId = UUID.randomUUID()var change = falseconstructor(pos: Int) {this.pos = pos}constructor() : this(0) {}}override fun onConfigurationChanged(newConfig: Configuration) {super.onConfigurationChanged(newConfig)Log.d("fly", "onConfigurationChanged")}
}
启动后,滑动到pos=30:
横竖屏切换,可以看到,Android自动在切换后把位置滚动到pos=30,无须recycleview再做滚动计算和调整:
日志:
Android重写onConfigurationChanged规避横竖屏切换时候重新进入onCreate生命周期-CSDN博客文章浏览阅读2.1k次。Android重写onConfigurationChanged规避横竖屏切换时候重新进入onCreate生命周期Android系统内在的机制,当activity在横竖屏切换时候,会强制重新开始进入activity的生命周期onCreate,在有些特殊的场景,开发者不希望重新进入onCreate生命周期,那么,可以通过重写Android的onConfigurationChanged规避。_onconfigurationchangedhttps://blog.csdn.net/zhangphil/article/details/50607742