gpt4 book ai didi

android - Kotlin:设置 TextView 时 lateinit 属性尚未初始化

转载 作者:行者123 更新时间:2023-11-30 04:57:34 25 4
gpt4 key购买 nike

我正在尝试在 fragment 中设置 TextView 的文本。我正在从我的 Pager Adapter 中的 Fragment 类调用一个方法来完成此操作,但我在这样做时收到以下错误:

Caused by: kotlin.UninitializedPropertyAccessException: lateinit property totalMsg has not been initialized

换句话说,似乎 onCreateView 方法在 setTotalMessages 被调用后被触发:下面是我的 TotalFragment 类的 Kotlin 代码:

class TotalFragment : Fragment() {
lateinit var inf:View;
lateinit var totalMsg:TextView;

override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View? {
// Inflate the layout for this fragment
inf = inflater!!.inflate(R.layout.total_fragment, container, false) as View;
totalMsg = inf.findViewById(R.id.chat_count)
Log.i("App", "done")
return inf;
}

// Setter method that sets the text of the total messages #
fun setTotalMessages(messageCount: String) : Unit {
Log.i("App", "done2")
totalMsg.text = "total # of messages exchanged: " + messageCount;
//totalMessages.setText("total # of messages exchanged: " + messageCount);
}
}

下面是我的寻呼机适配器代码:

class PageAdapter(private val myContext: Context, fm: FragmentManager, internal var totalTabs: Int) : FragmentPagerAdapter(fm) {
// keep track of the fragment containing the cumulative statistics
var totalFrag:TotalFragment = TotalFragment();

// this is for fragment tabs
override fun getItem(position: Int): Fragment? {
when (position) {
0 -> {
return totalFrag
}
1 -> {
return IndividualFragment()
}
2 -> {
// val movieFragment = MovieFragment()
return UsageFragment()
}
else -> return null
}
}

// set the text of the cumulative texts label
fun setCumulativeTexts(messageCount:Int) {
totalFrag.setTotalMessages(messageCount.toString());
}

// this counts total number of tabs
override fun getCount(): Int {
return totalTabs
}
}

下面是我的 MainActivity.kt 的 Kotlin 代码,我在其中调用方法来设置累积文本:

val adapter = PageAdapter(this, supportFragmentManager, tabLayout!!.tabCount)
adapter.setCumulativeTexts(5)

最佳答案

仅使用 var 而不是 lateinit var

var inf: View? = null
var totalMsg: TextView? = null
var messageCount: String? = null

然后像下面这样使用它

fun setTotalMessages(messageCount: String) : Unit { 
//store count here
this.messageCount = messageCount
totalMsg?.text = "total # of messages exchanged: " + messageCount
}

然后在创建 View 后尝试设置计数

override fun onCreateView( inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle? ): View? { 
inf = inflater!!.inflate(R.layout.total_fragment, container, false) as View;
totalMsg = inf?.findViewById(R.id.chat_count)

// set it from here
totalMsg?.text = "total # of messages exchanged: " + messageCount

return inf;
}

关于android - Kotlin:设置 TextView 时 lateinit 属性尚未初始化,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58870259/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com