android 不保存滚动位置

92dk7w1h  于 2023-09-28  发布在  Android
关注(0)|答案(1)|浏览(87)

我在努力实现一个简单的任务:我需要一个随机数时,按下按钮,当屏幕旋转,数字和滚动位置被保留。但由于某种原因,我无法实现这个功能,滚动位置没有保存。会是什么原因呢?

class MainActivity : AppCompatActivity() {
        override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
            if (savedInstanceState != null){
                val scrollPosition = savedInstanceState.getInt("scrollPosition")
                val scrollView = findViewById<ScrollView>(R.id.scrollView)
                scrollView.post { scrollView.scrollTo(0, scrollPosition) }
                val count = savedInstanceState.getInt("viewsCount")
                for (i in 0 until count)
                    addTextView()
            }
    
        }
    
        fun buttonAddClick(view: View) {
    
            addTextView()
    
    
        }
    
        private var viewsCount = 0
    
        fun addTextView() {
    
            viewsCount = rand(1..100)
            val textView = TextView(this)
            textView.text = viewsCount.toString()
            textView.textSize = 20f
            val container = findViewById<LinearLayout>(R.id.innerConteiner)
            container.addView(textView)
    
        }
    
    
    
        override fun onSaveInstanceState(outState: Bundle) {
            super.onSaveInstanceState(outState)
            outState.putInt("viewsCount", viewsCount)
            outState.putInt("scrollposition", findViewById<ScrollView>(R.id.scrollView).scrollY)
        }
    
    
        fun rand(range: IntRange): Int {
            require(range.first <= range.last) { "Illegal Argument" }
            return Random(System.nanoTime()).nextInt(range) + range.first
        }
    
    }
4ktjp1zp

4ktjp1zp1#

我没有检查代码,但我认为这是一个错字
检索时使用**“scrollPosition”**

val scrollPosition = savedInstanceState.getInt("scrollPosition")

但在保存时,您正在使用**“scrollposition”**

outState.putInt("scrollposition", findViewById<ScrollView>(R.id.scrollView).scrollY)

相关问题