创建片段时未设置TextView

时间:2018-09-16 18:55:58

标签: android android-fragments kotlin

这是我有关堆栈溢出的第一个问题,因此,如果我以不正当的方式提出要求,请提前道歉。

我正在尝试在Kotlin中创建一个基本应用程序,其中有一个包含一些片段的汉堡菜单。当用户单击HomeFragment时,我想显示一条欢迎消息,并带有他的名字(存储在“共享首选项”对象中)。

但是,每次我单击菜单按钮打开该片段时,它都会崩溃-即使我删除了整个用户名/共享的首选项,而只是尝试设置一些纯文本。

这是我的HomeFragment.kt文件:

package com.urmilshroff.kotlindemo

import android.content.Context
import android.net.Uri
import android.os.Bundle
import android.support.v4.app.Fragment
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import kotlinx.android.synthetic.main.fragment_home.*


private const val ARG_PARAM1="param1"
private const val ARG_PARAM2="param2"

class HomeFragment:Fragment()
{
    private var param1:String?=null
    private var param2:String?=null
    private var listener:OnFragmentInteractionListener?=null

    override fun onCreate(savedInstanceState:Bundle?)
    {
        super.onCreate(savedInstanceState)
        arguments?.let {
            param1=it.getString(ARG_PARAM1)
            param2=it.getString(ARG_PARAM2)
        }

    }

    override fun onCreateView(inflater:LayoutInflater,container:ViewGroup?,
                              savedInstanceState:Bundle?):View?
    {
        super.onCreate(savedInstanceState)

        val username=SharedPrefObj.getUsername(this.activity!!)
        textViewHello.text="Hi there, $username!"

        return inflater.inflate(R.layout.fragment_home,container,false)
    }

    fun onButtonPressed(uri:Uri)
    {
        listener?.onFragmentInteraction(uri)
    }

    override fun onAttach(context:Context)
    {
        super.onAttach(context)
        if(context is OnFragmentInteractionListener)
        {
            listener=context
        }
        else
        {
            throw RuntimeException(context.toString()+" must implement OnFragmentInteractionListener")
        }
    }

    override fun onDetach()
    {
        super.onDetach()
        listener=null
    }

    interface OnFragmentInteractionListener
    {
        fun onFragmentInteraction(uri:Uri)
    }

    companion object
    {
        @JvmStatic
        fun newInstance()=
                HomeFragment().apply {
                    arguments=Bundle().apply {
                        putString(ARG_PARAM1,param1)
                        putString(ARG_PARAM2,param2)
                    }
                }
    }
}

我的fragment_home.xml,以防万一:

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <android.support.constraint.ConstraintLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <TextView
            android:id="@+id/textViewHello"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:layout_marginTop="8dp"
            android:fontFamily="monospace"
            android:textAlignment="center"
            android:textColor="@color/colorAccent"
            android:textSize="30sp"
            app:layout_constraintBottom_toTopOf="@+id/textViewDesc"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="0.993" />

        <TextView
            android:id="@+id/textViewDesc"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginBottom="240dp"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:fontFamily="monospace"
            android:text="@string/text_view_desc"
            android:textAlignment="center"
            android:textSize="20sp"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintHorizontal_bias="0.503"
            app:layout_constraintStart_toStartOf="parent" />

    </android.support.constraint.ConstraintLayout>
</FrameLayout>

崩溃日志:

09-17 00:19:24.968 25279-25279/com.urmilshroff.kotlindemo E/AndroidRuntime: FATAL EXCEPTION: main
    Process: com.urmilshroff.kotlindemo, PID: 25279
    java.lang.IllegalStateException: textViewHello must not be null
        at com.urmilshroff.kotlindemo.HomeFragment.onCreateView(HomeFragment.kt:37)
        at android.support.v4.app.Fragment.performCreateView(Fragment.java:2346)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1428)
        at android.support.v4.app.FragmentManagerImpl.moveFragmentToExpectedState(FragmentManager.java:1759)
        at android.support.v4.app.FragmentManagerImpl.moveToState(FragmentManager.java:1827)
        at android.support.v4.app.BackStackRecord.executeOps(BackStackRecord.java:797)
        at android.support.v4.app.FragmentManagerImpl.executeOps(FragmentManager.java:2596)
        at android.support.v4.app.FragmentManagerImpl.executeOpsTogether(FragmentManager.java:2383)
        at android.support.v4.app.FragmentManagerImpl.removeRedundantOperationsAndExecute(FragmentManager.java:2338)
        at android.support.v4.app.FragmentManagerImpl.execPendingActions(FragmentManager.java:2245)
        at android.support.v4.app.FragmentManagerImpl$1.run(FragmentManager.java:703)
        at android.os.Handler.handleCallback(Handler.java:790)
        at android.os.Handler.dispatchMessage(Handler.java:99)
        at android.os.Looper.loop(Looper.java:164)
        at android.app.ActivityThread.main(ActivityThread.java:6494)
        at java.lang.reflect.Method.invoke(Native Method)
        at com.android.internal.os.RuntimeInit$MethodAndArgsCaller.run(RuntimeInit.java:438)
        at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:807)

它说textViewHello不能为null,因此我尝试使其变为可为null,但它崩溃了。不知道怎么了。感谢您的任何帮助,谢谢!

5 个答案:

答案 0 :(得分:2)

textViewHello尚未初始化。

像这样初始化它:

val rootView = inflater.inflate(R.layout.fragment_home,container,false) 
val textViewHello: TextView = rootView.findViewById(R.id.textViewHello) as TextView

在textview上设置文本之前添加以上行

最终onCreateView如下所示:

    super.onCreate(savedInstanceState)
    val rootView = inflater.inflate(R.layout.fragment_home,container,false) 
    val username=SharedPrefObj.getUsername(this.activity!!)
    val textViewHello: TextView = rootView.findViewById(R.id.textViewHello) as TextView
    textViewHello.text="Hi there, $username!"
    return rootView;

答案 1 :(得分:1)

您在项目中使用Kotlin Android Extentions,因此不再需要调用findViewById方法。

您需要做的就是将代码更改为:

override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?,
                          savedInstanceState: Bundle?): View? {
    super.onCreate(savedInstanceState)
    return inflater.inflate(R.layout.fragment_home, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    val username = SharedPrefObj.getUsername(this.activity!!)
    textViewHello.text = "Hi there, $username!"
}

答案 2 :(得分:0)

onViewCreated方法放在行下方。您需要重写该方法。

textViewHello.text="Hi there, $username!"

这将在onCreateView中启动文本视图后设置

答案 3 :(得分:0)

您需要在onViewCreated中使用它。

重写乐趣onCreateView(inflater:LayoutInflater,容器:ViewGroup ?, saveInstanceState:Bundle?):视图? {         return inflater.inflate(R.layout.qr_my_fragment,container,false)     }

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    super.onViewCreated(view, savedInstanceState)
    init()
}

private fun init() {
    setQRCode()
    initToolbar()
    clickEvents()
}

答案 4 :(得分:-1)

您试图调用方法setText,但是您的TextView对象实际上为null。您需要初始化。 在设置文本之前,您应该采取一些步骤。 1.在变量中填充视图

val view = inflater.inflate(R.layout.fragment_home,container,false)

2。查找并使用类变量连接xml对象

val textView: TextView = view.findViewById(R.id.textViewHello)

3。现在,您可以调用setText

textView.setText("Example text")

只需修改您的onCreateView方法

val view = inflater.inflate(R.layout.fragment_home,container,false)
val textView: TextView = view.findViewById(R.id.textViewHello)
textView.setText("Example text")