如何在android中使用kotlin获取片段中的资源ID?

时间:2017-09-26 06:21:56

标签: android kotlin

我尝试使用下面提到的代码,但在运行时遇到崩溃。发生的错误是Android运行时:

  

FATAL EXCEPTION:main进程:com.root.specialbridge,PID:17706 kotlin.KotlinNullPointerException at com.root.specialbridge.fragments.profile_fragment.WallFragments.initializeView(WallFragments.kt:49)

class WallFragments : Fragment(){

private var wallAdapter: WallAdapter? = null
private var wall_recycler: RecyclerView? = null
private val wallArrayList: ArrayList<Wall>? = null
private var mainlayout: LinearLayout? = null
private var no_result_found_layout: RelativeLayout? = null
private var userProfileWallInterface: UserProfileWallInterface? = null
internal var wallActivityBeanse: MutableList<WallActivityBeans> = ArrayList()

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
    val view = inflater!!.inflate(R.layout.wall_fragments, container, false)
    userProfileWallInterface = UserProfileWallPresentation(activity, this)
    initializeView()
    wallAdapter = WallAdapter(activity, wallActivityBeanse)
    wall_recycler!!.adapter = wallAdapter

    return view
}
fun initializeView() {
    wall_recycler = view!!.findViewById(R.id.wall_recycler_id) as RecyclerView
    mainlayout = view!!.findViewById(R.id.mainlayout) as LinearLayout
    no_result_found_layout = view!!.findViewById(R.id.no_result_found_layout) as RelativeLayout
    wall_recycler!!.layoutManager = LinearLayoutManager(activity)
    wall_recycler!!.setHasFixedSize(true)
    if (AuthPreference(activity).isGetMemberProfile) {
        userProfileWallInterface!!.getMemberProfileWall(view!!)

    } else {
        userProfileWallInterface!!.getUserProfileWall(AuthPreference(activity).token, AuthPreference(activity).user.id, view!!)

    }
}   
companion object {
    val instance: WallFragments
        get() = WallFragments()  }}

3 个答案:

答案 0 :(得分:14)

添加

apply plugin: 'kotlin-android-extensions'

在app level gradle文件和

导入

import kotlinx.android.synthetic.main.fragment_your_fragment_name.view.*

在您的片段的onCreateView中(例如,如果您的textview的ID是textView)

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
    // Inflate the layout for this fragment
    val view = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
    view.textView.text = "hello"   //add your view before id else getting nullpointer exception
    return view
}

<强>更新

在您的类中声明viewOfLayout而不是view。

class yourfragment:Fragment(){

    private lateinit var viewOfLayout: View
    override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
                              savedInstanceState: Bundle?): View? {
        // Inflate the layout for this fragment
        viewOfLayout = inflater!!.inflate(R.layout.fragment_splashfragment, container, false)
        viewOfLayout.textView.text = "hello"   //add your view before id else will get nullpointer exception
        return viewOfLayout
    }

}

答案 1 :(得分:6)

片段中视图的初始化:

wall_recycler=view.findViewById<RecyclerView>(R.id.wall_recycler_id)
mainlayout = view.findViewById<LinearLayout>(R.id.mainlayout)

问题是您过早访问它。 getView()viewonCreateView中返回null。我在onViewCreated()中找到了所有观看次数。 尝试使用onViewCreated方法:

 override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {

 wall_recycler=getView().findViewById<RecyclerView>(R.id.wall_recycler_id)
 mainlayout = getView().findViewById<LinearLayout>(R.id.mainlayout)
 mainlayout.setOnClickListener { Log.d(TAG, "onViewCreated(): hello world");}
    }

答案 2 :(得分:6)

介绍Kotlin Android Extensions

您不必再使用findViewById了。使用此插件,您可以将UI组件直接用作全局字段。 Activitiesfragmentsviews支持。

实施例, 要从下面的布局中引用文本视图,

<android.support.constraint.ConstraintLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <TextView
        android:id="@+id/hello"
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="Hello World, MyActivity"/>

</android.support.constraint.ConstraintLayout>

在活动中你可以简单地写,

// Using R.layout.activity_main from the main source set
import kotlinx.android.synthetic.main.activity_main.*

class MyActivity : Activity() {
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        // Instead of findViewById(R.id.hello) as TextView
        hello?.setText("Hello, world!")
    }
}

而且,除非您明确要!!,否则不应在任何地方使用NullPointerException

而是使用以下任何人:

  1. 使用安全通话进行空检查 - ?.,例如。 nullableVariable?.method()
  2. 使用?.let{ }的非空对象,例如。 nullableVariable?.let { nonNullVariable.method() }
  3. 使用elvis运算符为{ - 1}}提供可空变量的备份值,例如。 ?:
  4. 详细了解Null Safety in Kotlin