首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何使用android中的kotlin从片段中获取资源id?

如何使用android中的kotlin从片段中获取资源id?
EN

Stack Overflow用户
提问于 2017-09-26 06:21:56
回答 3查看 49.7K关注 0票数 18

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

致命异常:主进程: com.root.specialbridge,PID: com.root.specialbridge.fragments.profile_fragment.WallFragments.initializeView(WallFragments.kt:49):17706 kotlin.KotlinNullPointerException

代码语言:javascript
复制
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()  }}
EN

回答 3

Stack Overflow用户

发布于 2017-12-08 06:31:53

添加

apply plugin: 'kotlin-android-extensions'

在应用程序级别的gradle文件和

导入

代码语言:javascript
复制
import kotlinx.android.synthetic.main.fragment_your_fragment_name.view.*

在片段的onCreateView中(例如,如果文本视图的id是textView)

代码语言:javascript
复制
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。

代码语言:javascript
复制
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
    }

}
票数 33
EN

Stack Overflow用户

发布于 2017-09-26 08:41:10

介绍了Kotlin Android扩展

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

例如,要从下面的布局引用文本视图,

代码语言:javascript
复制
<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>

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

代码语言:javascript
复制
// 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!")
    }
}

碎片,

代码语言:javascript
复制
// 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!")
    }
}

为了表达意见,

代码语言:javascript
复制
// 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)
    }

}

而且,除非您想要显式地使用!!,否则不应该在任何地方都使用NullPointerException

相反,请使用以下内容中的任何人:

  1. 使用安全调用- ?.进行空检查,例如。nullableVariable?.method()
  2. 使用?.let{ }使用非空对象,例如。nullableVariable?.let { it.method() }
  3. 使用elvis操作符- ?:为可空变量提供备份值,例如。nullableVariable ?: <backupValue>

阅读更多关于Kotlin中的空安全的信息。

票数 13
EN

Stack Overflow用户

发布于 2017-09-26 07:22:13

以片段形式初始化视图:

代码语言:javascript
复制
wall_recycler=view.findViewById<RecyclerView>(R.id.wall_recycler_id)
mainlayout = view.findViewById<LinearLayout>(R.id.mainlayout)

问题是你访问它太快了。requireView()viewonCreateView中返回null,.I查找onViewCreated()中的所有视图。尝试在onViewCreated方法中这样做:

代码语言:javascript
复制
 override fun onViewCreated(view: View?, savedInstanceState: Bundle?) {

 wall_recycler=requireView().findViewById<RecyclerView>(R.id.wall_recycler_id)
 mainlayout = requireView().findViewById<LinearLayout>(R.id.mainlayout)
 mainlayout.setOnClickListener { Log.d(TAG, "onViewCreated(): hello world");}
    }
票数 10
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/46419171

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档