简体   繁体   English

片段内的 Android Kotlin Recyclerview 为空

[英]Android Kotlin Recyclerview inside fragment is null

I can't get my Recycleview inside my fragment to work.我无法让我的片段中的 Recycleview 工作。 I've tried moving the recyclerview adapter and layout code to onViewCreated but that didn't work either.我尝试将 recyclerview adapterlayout代码移动到onViewCreated但这也不起作用。

Does anybody have an idea to what the problem could be?有没有人知道问题可能是什么?

Main Activity主要活动

...
 override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        setContentView(R.layout.activity_main)
        setSupportActionBar(toolbar)
        loadFragment(NewsFragment()) // Show the news fragment by default
        initBottomNavigation()
}
...
private fun loadFragment(fragment: Fragment) {
        val transaction = supportFragmentManager.beginTransaction()
        transaction.replace(R.id.fragment_container, fragment)
        transaction.addToBackStack(null)
        transaction.commit()
}
...

NewsAdapter新闻适配器

class NewsAdapter(private val newsItems: List<NewsItem>) :
    RecyclerView.Adapter<NewsAdapter.ViewHolder>() {

    private lateinit var context: Context

    override fun onCreateViewHolder(parent: ViewGroup, viewType: Int): ViewHolder {
        context = parent.context

        return ViewHolder(
            LayoutInflater.from(context).inflate(R.layout.news_list_item, parent, false)
        )
    }

    override fun getItemCount(): Int = newsItems.size

    override fun onBindViewHolder(holder: ViewHolder, position: Int) =
        holder.bind(newsItems[position])

    inner class ViewHolder(itemView: View) : RecyclerView.ViewHolder(itemView) {

        fun bind(newsItem: NewsItem) {

        }
    }
}

fragment_news.xml fragment_news.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"
    tools:context=".NewsFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvNewsItems"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

        <include
            layout="@layout/news_list_item"
            android:layout_width="match_parent"
            android:layout_height="wrap_content" />
    </androidx.recyclerview.widget.RecyclerView>

</FrameLayout>

NewsFragment新闻片段

class NewsFragment : Fragment() {

    private val newsItems = arrayListOf<NewsItem>()
    private val newsAdapter = NewsAdapter(newsItems)

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        if (container != null) {
            container.rootView.rvNewsItems.layoutManager =
                LinearLayoutManager(context, RecyclerView.VERTICAL, false)
            container.rootView.rvNewsItems.adapter = newsAdapter
        }

        // Inflate the layout for this fragment
        return inflater.inflate(R.layout.fragment_news, container, false)
    }

    override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
        btnLike.setOnClickListener {
            val color = ResourcesCompat.getColor(resources, R.color.colorPrimary, null);
            btnLike.setColorFilter(color)
        }
    }

}

build.gradle构建.gradle

apply plugin: 'com.android.application'

apply plugin: 'kotlin-android'

apply plugin: 'kotlin-android-extensions'

android {
    compileSdkVersion 29
    buildToolsVersion "29.0.2"
    defaultConfig {
        applicationId "com.example.johanvanderlindenapp"
        minSdkVersion 21
        targetSdkVersion 29
        versionCode 1
        versionName "1.0"
        testInstrumentationRunner "androidx.test.runner.AndroidJUnitRunner"
    }
    buildTypes {
        release {
            minifyEnabled false
            proguardFiles getDefaultProguardFile('proguard-android-optimize.txt'), 'proguard-rules.pro'
        }
    }
}

dependencies {
    implementation fileTree(dir: 'libs', include: ['*.jar'])
    implementation "org.jetbrains.kotlin:kotlin-stdlib-jdk7:$kotlin_version"
    implementation 'androidx.appcompat:appcompat:1.1.0'
    implementation 'androidx.core:core-ktx:1.1.0'
    implementation 'androidx.constraintlayout:constraintlayout:1.1.3'
    implementation 'androidx.legacy:legacy-support-v4:1.0.0'
    testImplementation 'junit:junit:4.12'
    androidTestImplementation 'androidx.test.ext:junit:1.1.1'
    androidTestImplementation 'androidx.test.espresso:espresso-core:3.2.0'

    //Navigation
    implementation "androidx.navigation:navigation-fragment-ktx:2.1.0"
    implementation "androidx.navigation:navigation-ui-ktx:2.1.0"

    // Material widgets
    implementation "com.google.android.material:material:1.0.0"

    // ViewModel and LiveData
    def lifecycle_version = "2.1.0"
    implementation "androidx.lifecycle:lifecycle-extensions:$lifecycle_version"

    implementation 'androidx.recyclerview:recyclerview:1.1.0'
}

EDIT I have removed the include inside the recycleview shown above, still receive the error.编辑我已经删除了上面显示的 recycleview 中的包含,仍然收到错误。

Try this尝试这个

    <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"
    tools:context=".NewsFragment">

<androidx.recyclerview.widget.RecyclerView
    android:id="@+id/rvNewsItems"
    android:scrollbars="vertical"
    android:layout_width="match_parent"
    android:orientation="vertical"
    app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
    android:layout_height="match_parent" >

</androidx.recyclerview.widget.RecyclerView>





class NewsFragment : Fragment() {

    private val newsItems = arrayListOf<NewsItem>()
    private val newsAdapter : NewsAdapter? = null

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

        container.rootView.rvNewsItems.adapter = newsAdapter
        container.rootView.rvNewsItems.adapter as NewsAdapter).submitList(newsItems)

    }

    // Inflate the layout for this fragment
    return inflater.inflate(R.layout.fragment_news, container, false)
}

override fun onViewCreated(view: View, savedInstanceState: Bundle?) {
    btnLike.setOnClickListener {
        val color = ResourcesCompat.getColor(resources, R.color.colorPrimary, null);
        btnLike.setColorFilter(color)
    }
}

You cannot use the <include /> tag to show your list items.您不能使用<include />标签来显示您的列表项。 Your ViewHolder class takes care of instantiating your list items for you.您的ViewHolder类负责为您实例化您的列表项。 Simply remove the include tag in your fragment_news.xml :只需删除fragment_news.xml中的include标签:

<?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"
    tools:context=".NewsFragment">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/rvNewsItems"
        android:scrollbars="vertical"
        android:layout_width="match_parent"
        android:layout_height="match_parent" >

    </androidx.recyclerview.widget.RecyclerView>

</FrameLayout>

Also, make sure your newsItems is not empty.另外,请确保您的newsItems不为空。 Otherwise, it will show you an empty view.否则,它将显示一个空视图。 If you wish to add items to your newsItems , don't forget to call notifyDataSetChanged() in your adapter to reflect the changes.如果您希望向您的newsItems添加项目,请不要忘记在您的适配器中调用notifyDataSetChanged()以反映更改。

Using vindViewById instead of synthetic turned out to solve the problem.原来使用vindViewById而不是synthetic来解决这个问题。

My news fragment now looks like this:我的新闻片段现在看起来像这样:

class NewsFragment : Fragment() {

    private val newsItems = arrayListOf<NewsItem>()
    private val newsAdapter = NewsAdapter(newsItems)

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

        val view = inflater.inflate(R.layout.fragment_news, container, false)
        val rvNewsItems = view.findViewById(R.id.rvNewsItems) as RecyclerView

        rvNewsItems.layoutManager = LinearLayoutManager(context)
        rvNewsItems.adapter = newsAdapter

        return view
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM