为什么在 Adapter 中从另一个 activity 调用的函数总是 return false?

Why does function called in Adapter from another activity always return false?

ExamAcitivy 内幕:

passExamState 总是 returns false,即使它的值在 setOnClickListener 之后变为 true,当在适配器中调用时我需要它相应地 return 状态。我如何正确地将 examState 及其值传递给适配器?

class ExamActivity : AppCompatActivity(){

    private var examState  = false

    private val questionData = QuestionData()
    private var  questionAdapter = QuestionAdapter(questionData)

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

        questionViewPager.adapter = questionAdapter
  

        endExam.setOnClickListener {
           examState=true
        }
            
    }

    fun passExamState() : Boolean {
        return examState
    }
}

在我的 ViewPager2Adapter 内部:

class QuestionAdapter(private val questionData: QuestionData) :
RecyclerView.Adapter<QuestionAdapter.QuestionViewPagerViewHolder>() {

inner class QuestionViewPagerViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView){

   //itemviews

    init {
        if (!ExamActivity().passExamState()) {
            getthis()
        }else{
            getthat()
        }
    }

}


override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): QuestionViewPagerViewHolder {
    return QuestionViewPagerViewHolder(
        LayoutInflater.from(parent.context).inflate(R.layout.item_question, parent, false)
    )
}

override fun onBindViewHolder(holder: QuestionViewPagerViewHolder, position: Int) {

  

    //itemviews

    if (!ExamActivity().passExamState()){
        dothis()
    }else{
        dothat()

    }


}

//项目数 }

问题是您正在创建一个新的考试Activity 实例并使用该实例的属性 来检查passExamState()。在这一行中,它在您的代码中出现了两次:

if (!ExamActivity().passExamState()) {

您正在调用 ExamActivity 构造函数来构造一个新的 Activity,因此您没有检查屏幕上实际 Activity 的状态。

执行此操作的正确封装方法是在您的适配器中创建适当的布尔值 属性,并允许您的 Activity 修改该 属性。这种组织代码的方式减少了相互依赖。适配器不必知道 Activity 的存在。例如:

//In ExamActivity:

endExam.setOnClickListener {
    examState = true // If you even need to track this property in the Activity.
                     // Maybe you can remove the property entirely.

    questionAdapter.examState = true
}

// Adapter class:

class QuestionAdapter(private val questionData: QuestionData) :
RecyclerView.Adapter<QuestionAdapter.QuestionViewPagerViewHolder>() {
   
    var examState = false

    inner class QuestionViewPagerViewHolder(itemView: View) : 
    RecyclerView.ViewHolder(itemView) {

        init {
            if (!examState) { // and the same in onBindViewHolder
                getthis()
            }else{
                getthat()
            }
       }

    }

    //...

}