IllegalStateException:NavigationDrawer活动中的Fragment内的RecyclerView为null

时间:2018-01-26 09:53:27

标签: android android-fragments kotlin

我试图制作一个RecyclerView,它将进入我片段的两个页面之一。这些页面放在NavigationDrawer活动中。目标是创建类似Play商店应用主页的内容。

但是我在运行时的代码片段中发现了一个错误。它说:

java.lang.IllegalStateException: mainMenu must not be null
    at com.example.MyApp.app.fragment.MainFragment.onCreate(MainFragment.kt:49)

我一直在寻找一些SO线程,他们说布局没有正确加载。这导致一些元素没有被链接起来。另一位在评论中说,问题在于上下文未正确初始化。对我来说情况并非如此(相反,它是RecyclerView)。

以下是链接,希望它们可以作为参考。

在对我的代码进行多次检查后,我发誓我已将正确的布局放入。编辑:我导入了 kotlinx.android.synthetic.main.^ 包,我把这个标志放在:^ $ {layout}。这是我的一些文件(如果这个帖子太长,请原谅我):

  • MainActivity.kt : AppCompatActivity() ^ activity_main。*

    override fun onCreate(savedInstanceState: Bundle?) {
            super.onCreate(savedInstanceState)
            setContentView(R.layout.activity_main)
    
            // preparing the app bars
            setSupportActionBar(toolBar)
    
            // getting ready for the pages
            val pagerAdapter = MainPagerAdapter(
                    supportFragmentManager,
                    resources.getString(R.string.tab_main),
                    resources.getString(R.string.tab_chat)
            )
            pager.adapter = pagerAdapter
    
            // activating tabs
            tabLayout.setupWithViewPager(pager)
    
            val toggle = ActionBarDrawerToggle(
                    this, mainDrawer, toolbar,
                    R.string.navigation_drawer_open,
                    R.string.navigation_drawer_close)
    
            mainDrawer.addDrawerListener(toggle)
    
    
            navView.setNavigationItemSelectedListener(this)
            toggle.syncState()
    
    }
    
  • MainPagerAdapter.kt (fm: FragmentManager, private val page1: String, private val page2: String): FragmentPagerAdapter(fm)

    override fun getItem(position: Int): Fragment? {
        return when (position) {
            0 -> MainFragment()
            1 -> ChatFragment()
            else -> null
        }
    }
    
    override fun getCount() = 2
    
    override fun getPageTitle(position: Int): CharSequence? {
        return when (position) {
            0 -> page1
            1 -> page2
            else -> null
        }
    }
    
  • MainFragment.kt : Fragment() ^ content_main。*

    override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?)
        : View? = inflater.inflate(R.layout.content_main, container)
    
    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
    
        // this is the error
        mainMenu.layoutManager = LinearLayoutManager(this.context)
    
        mainMenu.adapter = MyAdapter(itemList) {
            toast("${it.name} selected")
        }
    }
    
  • MyAdapter.kt: RecyclerView.Adapter<MyAdapter.MyHolder>() ^ item_custom.view。* (由Antonio Leiva提供)

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int)
        = GoodsHolder(parent.inflate(R.layout.item_custom))
    
    override fun getItemCount()
        = itemList.size
    
    override fun onBindViewHolder(holder: MyHolder, position: Int)
        = holder.bind(itemList[position], listener)
    
    
    class MyHolder(v: View): RecyclerView.ViewHolder(v){
        private val item: Item? = null
        private val view = v
    
        fun bind(item: Item, listener: (Item) -> Unit)
                = with (itemView) {
            imgPic.setImageResource(item.pictureId)
            txtName.text = item.name
            txtPrice.text = item.price.toString()
    
        setOnClickListener { listener(item) }
        }
    }
    
  • content_main.xml

    <android.support.constraint.ConstraintLayout
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto"
        xmlns:tools="http://schemas.android.com/tools"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        app:layout_behavior="@string/appbar_scrolling_view_behavior"
        tools:context="com.example.MyApp.app.activity.MainActivity"
        >
    
        <!-- the RecyclerView that caused the runtime error -->
        <android.support.v7.widget.RecyclerView
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/mainMenu"/>
    
    </android.support.constraint.ConstraintLayout>
    
  • item_custom.xml(这些代码位于CardView内的LinearLayout内)

    <ImageView
        android:id="@+id/imgPic"
        android:layout_width="match_parent"
        android:layout_height="128dp"
        app:srcCompat="@drawable/ic_menu_gallery" />
    
    <TextView
        android:id="@+id/txtName"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Get it while it's hot!"
        android:layout_margin="@dimen/margin_small"
        android:layout_marginTop="@dimen/margin_medium"
        android:maxLines="2"
        android:ellipsize="end"
        android:textStyle="bold"
        />
    
    <TextView
        android:id="@+id/txtPrice"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="$3.000.000"
        android:layout_marginLeft="@dimen/margin_small"
        android:layout_marginStart="@dimen/margin_small"
        android:layout_marginRight="@dimen/margin_small"
        android:layout_marginEnd="@dimen/margin_small"
        android:layout_marginBottom="@dimen/margin_medium"/>
    
  • ChatFragment.kt:Fragment()(仅包含onCreateView inflating content_main_chat.xml)

  • content_main_chat.xml(仅包含TextView)

8 个答案:

答案 0 :(得分:5)

您尚未在MainFragment.kt文件中初始化RecyclerView。你必须在下面的行之前初始化它:

mainMenu.layoutManager = LinearLayoutManager(this.context)

您可以通过以下行初始化RecyclerView:

var mainMenu = findViewById(R.id.mainMenu) as RecyclerView

您必须根据需要进行更改。

答案 1 :(得分:3)

对于那些遵循@Avijit Karmakar精采线索的人,请多加讨论,(RecyclerView error: No adapter attached; skipping layout) 我必须包括:

class WikiFragment : Fragment() {
    val paginas: ArrayList<String> = ArrayList()    

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

var rv_frag_wiki = listItems.findViewById<View>(R.id.rv_frag_wiki) as RecyclerView


 rv_frag_wiki.layoutManager = LinearLayoutManager(this.context)
        rv_frag_wiki.adapter = PaginasAdapter(paginas, this.context)
        
  return listItems 
  

答案 2 :(得分:0)

您忘记初始化mainMenu onCreate内的MainFragment.kt

答案 3 :(得分:0)

设置recyclerView的layoutManager

mainMenu.layoutManager = LinearLayoutManager(this.context)

此状态您的recyclerView尚未初始化,因此您必须明确初始化recyclerView

val mainMenu = view.findViewById(R.id.recyclerView) as RecyclerView

答案 4 :(得分:0)

我认为初始化onViewCreated中的元素是一种更好的方法,例如@Egor Neliuba所讲授的: NullPointerException when trying to access views in a Kotlin fragment

答案 5 :(得分:0)

如果您正在使用片段:1.使用一个全局变量来保存布局参考

internal var root: View? = null   // create a global variable which will hold your layout override fun onCreateView(inflater: LayoutInflater, container: ViewGroup?, savedInstanceState: Bundle?): View? {
        root = inflater.inflate(R.layout.your_layout_file_name, container, false)  // initialize it here
        return root
}
  1. 要使用布局内部的任何视图,可以将其与(root。)一起使用:

    root!!.recyclerView.layoutManager = LinearLayoutManager(context,LinearLayoutManager.VERTICAL, false)
    

答案 6 :(得分:0)

由于您使用的是Kotlin,因此无需使用var rv_frag_wiki = listItems.findViewById<View>(R.id.rv_frag_wiki) as RecyclerView

就可以利用合成材料的优势

通过插件导入合成 第1步:

apply plugin: 'kotlin-android'
apply plugin: 'kotlin-android-extensions'

第2步:

在MainFragment中导入音色

import kotlinx.android.synthetic.main.content_menu.* //

第3步:

最后进入MainFragment

在此处移动recyclerView的代码

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

        rvList.layoutManager = LinearLayoutManager(context, 
        LinearLayoutManager.VERTICAL, false)
        rvList.adapter = academyAdapter

    }

答案 7 :(得分:0)

   = note: expected `&mut TimerQueue`
              found `&mut TimerQueue`

以下链接在我的情况下有效。

https://www.manongdao.com/q-596674.html