当前位置: 首页 > article >正文

Android编程权威指南(第四版)- 第 4 章 UI状态的保存与恢复

文章目录

  • 代码:
    • 依赖
    • MainActivity
    • QuizViewModel
    • Question
    • 知识点

代码:

大体是一样的,修改了一些

依赖

    implementation("androidx.lifecycle:lifecycle-extensions:2.2.0")

MainActivity

package com.example.geoquiz

import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.view.View
import android.widget.Button
import android.widget.TextView
import android.widget.Toast
import androidx.lifecycle.ViewModelProviders
private const val KEY_INDEX = "index"
private const val KEY_SOCRE = "socre"
private const val KEY_BUTTONSTATUS="buttonStatus"
class MainActivity : AppCompatActivity() {
    private lateinit var questionText: TextView
    private lateinit var ture_button: Button
    private lateinit var false_button: Button
    private lateinit var last_button: Button
    private lateinit var next_button: Button
    private lateinit var score_button: Button
    private val TAG="MainActivity"

    private val quizViewModel: QuizViewModel by lazy {
        ViewModelProviders.of(this)[QuizViewModel::class.java]
    }


    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)

        val index= savedInstanceState?.getInt(KEY_INDEX,0)?:0
        quizViewModel.index=index


        questionText = findViewById(R.id.question)
        ture_button = findViewById(R.id.ture_button)
        false_button = findViewById(R.id.false_button)
        last_button = findViewById(R.id.last_button)
        next_button = findViewById(R.id.next_button)
        next_button = findViewById(R.id.next_button)
        score_button = findViewById(R.id.score_button)
        updateQuestion()
        //点击问题跳转下一题
        questionText.setOnClickListener(View.OnClickListener {
            quizViewModel.nextQuestion()
            updateQuestion()
        })

        ture_button.setOnClickListener(View.OnClickListener {
            quizViewModel.buttonStatus = false
            checkAnswer(true)
            closeButton()
        })

        false_button.setOnClickListener(View.OnClickListener {
            quizViewModel.buttonStatus = false
            checkAnswer(false)
            closeButton()
        })

        last_button.setOnClickListener(View.OnClickListener {
            openButton()
            quizViewModel.lastQuestion()
            updateQuestion()
        })

        next_button.setOnClickListener(View.OnClickListener {
            openButton()
            quizViewModel.nextQuestion()
            updateQuestion()
        })

        score_button.setOnClickListener(View.OnClickListener {
            settlementScore()
        })
    }

    override fun onStart() {
        super.onStart()
        Log.e(TAG, "onStart")
    }

    override fun onResume() {
        super.onResume()
        Log.e(TAG, "onResume")
    }

    override fun onPause() {
        super.onPause()
        Log.e(TAG, "onPause")
    }

    override fun onSaveInstanceState(outState: Bundle) {
        super.onSaveInstanceState(outState)
        Log.e(TAG,"onSaveInstanceState")
        //保存问题索引值
       outState.putInt(KEY_INDEX,quizViewModel.index)
    }

    override fun onStop() {
        super.onStop()
        Log.e(TAG, "onStop")
    }

    override fun onDestroy() {
        super.onDestroy()
        Log.e(TAG, "onDestroy")
    }

    private fun updateQuestion() {
        var textId = quizViewModel.questionIndex
        questionText.setText(textId)
    }

    private fun checkAnswer(answer: Boolean) {
        var questionanswer = quizViewModel.questionAnswer
        if (answer == questionanswer) {
            quizViewModel.score += 20
            Toast.makeText(this, R.string.ture_toast, Toast.LENGTH_SHORT).show()

        } else {
            Toast.makeText(this, R.string.false_toast, Toast.LENGTH_SHORT).show()

        }

    }

    private fun closeButton() {
        if (!quizViewModel.buttonStatus) {
            ture_button.isEnabled = quizViewModel.buttonStatus
            false_button.isEnabled = quizViewModel.buttonStatus
        }
    }

    private fun openButton() {
        if (!quizViewModel.buttonStatus) {
            ture_button.isEnabled = true
            false_button.isEnabled = true
        }
    }

    private fun settlementScore() {
        //答完所有题结算成绩
        if (quizViewModel.index == quizViewModel.listSize - 1) {
            Toast.makeText(this, "得分为${quizViewModel.score}", Toast.LENGTH_SHORT).show()
            quizViewModel.score = 0

        } else {
            Toast.makeText(this, "题目没有答完哦", Toast.LENGTH_SHORT).show()
        }
    }
}

QuizViewModel

package com.example.geoquiz

import androidx.lifecycle.ViewModel

class QuizViewModel : ViewModel() {
    var index = 0
    private var questionList = listOf(
        Question(R.string.question, true),
        Question(R.string.question1, true),
        Question(R.string.question2, true),
        Question(R.string.question3, false),
        Question(R.string.question4, false),
        Question(R.string.question5, false)
    )

    var buttonStatus = true//按钮可以按
    var score = 0
    val listSize = questionList.size

    val questionIndex: Int
        get() = questionList[index].questionID

    val questionAnswer: Boolean
        get() = questionList[index].answer

    fun nextQuestion() {
        index = (index + 1) % questionList.size
    }

    fun lastQuestion() {
        //       if (index == 0) {
//            index = questionList.size - 1
//        } else {
//            index -= 1
//        }
        index = if (index == 0) questionList.size - 1 else index - 1
    }

}

Question

package com.example.geoquiz

import androidx.annotation.StringRes

data class Question(@StringRes val questionID: Int, val answer: Boolean) {
}

知识点

ViewModelProviders类提供了ViewModelProvider实例,调用ViewModelProviders.of(this)创建并返回一个关联了MainActivity的ViewModelProvider实例,ViewModelProvider会提供ViewModel实例给MainActivity

activity被销毁的两种情况:

  1. 用户结束使用activity
  2. 因设备配置发送改变时系统销毁

http://www.kler.cn/a/234872.html

相关文章:

  • Linux学习笔记之组管理和权限管理
  • Linux下useradd 和 adduser的区别
  • Python数据分析NumPy和pandas(二十九、其他Python可视化工具)
  • 在Linux上部署(MySQL Redis Elasticsearch等)各类软件
  • C++实现用户分组--学习
  • C字符串 | 字符串处理函数 | 使用 | 原理 | 实现
  • 【WPF.NET开发】优化性能:其他建议
  • fast.ai 机器学习笔记(三)
  • 【开源】JAVA+Vue.js实现森林火灾预警系统
  • Rhino.Inside带材质将Revit模型bake到Rhino
  • 使用 FFmpeg 将视频转换为 GIF 动画的技巧
  • kafka教程
  • JavaWeb后端开发(第一期):Maven基础、Maven的安装配置、如何创建maven项目模块、maven的生命周期
  • 链表:反转链表
  • Flask 入门7:使用 Flask-Moment 本地化日期和时间
  • [ai笔记1] 借着“ai春晚”开个场
  • 第三百一十五回
  • [ai笔记3] ai春晚观后感-谈谈ai与艺术
  • Linux---网络套接字
  • Linux(Ubuntu) 环境搭建:Nginx
  • 【MySQL基础】:深入探索DQL数据库查询语言的精髓(上)
  • 创建你的第一个Vue项目(小白专享版本)
  • 《Django+React前后端分离项目开发实战:爱计划》 02 安装Python和Django
  • Pytorch 复习总结 1
  • 【深度学习】pytorch 与 PyG 安装(pip安装)
  • Python无人弹药