簡體   English   中英

任何人都可以幫助我為什么我得到 null 值即使代碼中沒有錯誤

[英]can anyone help me out why I am getting null value even there is no error in the code

package com.example.myquizapp
import androidx.appcompat.app.AppCompatActivity
import android.os.Bundle
import android.util.Log
import android.widget.ProgressBar
import android.widget.TextView

這是我的代碼

class QuizActivity : AppCompatActivity() {
    private var progressBar : ProgressBar?= null
    private var tvProgress : TextView? = null

    override fun onCreate(savedInstanceState: Bundle?) { 
            progressBar = findViewById(R.id.progressBar)  

在 hover R.id.progressBar 我得到:public static final int progressBar = 1000004

            tvProgress = findViewById(R.id.tv_progress)

// public static final int tv_progress = 100000

//在 hover progressBar 上我得到:private final var progressBar: ProgressBar?

            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_quiz)

            var currentPosition = 1
            progressBar?.progress=currentPosition                       
            tvProgress?.text="${currentPosition}/${progressBar?.max}"
            Log.e("currentPosition" "${currentPosition})        // 1
            Log.e("ProgressBar", "${progressBar}")    // null, getting null value on logcat
            Log.e("TvOrogress", "${tvProgress}")// null, getting null value on logcat
            Log.e("tvProgress",${tvProgress?.text.toString}  // null

    }
}

setContentView()之后移動findViewById()調用。

setContentView()膨脹視圖層次結構並將其添加到活動中。 findViewById()在活動視圖層次結構中查找視圖,並且在setContentView()之前為空,因此findViewById()返回 null。

將 findViewById() 移至 onViewCreated 方法

  override fun onViewCreated(savedInstanceState: Bundle?) { 
            progressBar = findViewById(R.id.progressBar) 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM