【发布时间】:2019-11-15 04:16:09
【问题描述】:
我正在尝试在片段中设置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)
【问题讨论】:
-
因为
setTotalMessages在onCreatView之前工作。所以你的 totalMsg 没有初始化。 -
您在代码中的哪个位置初始化并将
TotalFragment添加到容器视图中? -
说明你想做什么。我认为你可以用更合适的方式来实现你的目标
标签: android android-fragments kotlin