【问题标题】:Kotlin: lateinit property has not been initialized when setting TextViewKotlin:设置TextView时lateinit属性未初始化
【发布时间】: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)

【问题讨论】:

  • 因为setTotalMessagesonCreatView 之前工作。所以你的 totalMsg 没有初始化。
  • 您在代码中的哪个位置初始化并将TotalFragment 添加到容器视图中?
  • 说明你想做什么。我认为你可以用更合适的方式来实现你的目标

标签: android android-fragments kotlin


【解决方案1】:

仅使用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
}

然后在创建视图后尝试设置计数

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; 
} 

【讨论】:

  • 非常感谢,效果很好。一个非常聪明的解决方案!
  • 很高兴听到@Adam。请不要忘记按upvote,以便其他人可以发现它有帮助。谢谢
【解决方案2】:

你试过了吗?

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

您还可以从 R.layout.total_fragment 添加代码以更好地理解问题吗?

【讨论】:

    【解决方案3】:

    onCreateView膨胀视图时被调用。您应该在onViewCreated 方法中获取对您的视图的引用(即视图被膨胀之后)

    override fun onViewCreated(...) {
        totalMsg = inf.findViewById(R.id.chat_count)
    }
    

    【讨论】:

    猜你喜欢
    • 2020-04-14
    • 1970-01-01
    • 2022-11-22
    • 2021-10-13
    • 2022-07-05
    • 1970-01-01
    • 1970-01-01
    • 2021-02-01
    • 2017-03-03
    相关资源
    最近更新 更多