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

Ram*_*esh 11 android kotlin

我尝试了下面提到的这个代码,但在运行时遇到崩溃.发生的错误是Android运行时:

致命异常:主要进程: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()  }}
Run Code Online (Sandbox Code Playgroud)

Kir*_*eph 21

apply plugin: 'kotlin-android-extensions'

在应用程序级gradle文件和

进口

import kotlinx.android.synthetic.main.fragment_your_fragment_name.view.*
Run Code Online (Sandbox Code Playgroud)

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
}
Run Code Online (Sandbox Code Playgroud)

更新:

在您的类中声明viewOfLayout而不是视图.

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
    }

}
Run Code Online (Sandbox Code Playgroud)


Anc*_*ngh 7

片段中视图的初始化:

wall_recycler=view.findViewById<RecyclerView>(R.id.wall_recycler_id)
mainlayout = view.findViewById<LinearLayout>(R.id.mainlayout)
Run Code Online (Sandbox Code Playgroud)

问题是您访问它太早了。getView()并在中view返回null。onCreateView我在中找到了所有视图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");}
    }
Run Code Online (Sandbox Code Playgroud)


Kri*_*ish 5

介绍Kotlin Android扩展

您不必再使用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>
Run Code Online (Sandbox Code Playgroud)

在活动中,您只需编写,

// 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!")
    }
}
Run Code Online (Sandbox Code Playgroud)

零碎地

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

class ContentFragment : Fragment() {

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? =
        inflater.inflate(R.layout.fragment_content, container, false)

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        super.onViewCreated(view, savedInstanceState)
        // Instead of view.findViewById(R.id.hello) as TextView
        hello?.setText("Hello, world!")
    }
}
Run Code Online (Sandbox Code Playgroud)

对于意见,

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

class ItemViewHolder(view: View) : RecyclerView.ViewHolder(view) {

    fun bindData(data: String) {
        // Instead of itemView.findViewById(R.id.hello) as TextView
        itemView.hello?.setText(data)
    }

}
Run Code Online (Sandbox Code Playgroud)

并且,!!除非NullPointerException明确需要,否则不要在任何地方使用。

而是使用以下任何人:

  1. 用安全呼叫-进行空检查?.nullableVariable?.method()
  2. 例如,使用非null对象?.let{ }nullableVariable?.let { it.method() }
  3. 使用elvis运算子-提供可空变量的备用值?:,例如。nullableVariable ?: <backupValue>

在Kotlin上了解有关Null安全性的更多信息。