无法解析fragment recyclerview中的“findviewbyid”方法

xienkqul  于 2021-06-29  发布在  Java
关注(0)|答案(3)|浏览(544)

我是android工作室的新手,我试图在fragment上创建recyclerview。我在遵循一个教程,但我仍然得到消息'无法解决'findviewbyid'
我试过做:

RecyclerView recyclerView = (RecyclerView)getView().findViewById(R.id.recyclerView);

但最终收到错误:

Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference

代码如下:

package com.example.app;

import android.os.Bundle;

import androidx.fragment.app.Fragment;
import androidx.recyclerview.widget.RecyclerView;

import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

public class Articles extends Fragment {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        NewsList[] myListData = new NewsList[] {
                new NewsList("Article 1", "Some Author"),
                new NewsList("Article2", "Some Author"),
                new NewsList("Article3", "Some Author"),

        };
        RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerView);
        NewsAdapter adapter = new NewsAdapter(myListData);
        recyclerView.setHasFixedSize(true);
        recyclerView.setAdapter(adapter);

    }
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {

        return inflater.inflate(R.layout.fragment_create, container, false);
    }

}

如何解决此问题?

piah890a

piah890a1#

例如,list(mylistdatae)必须作为字段变量位于newsadapter类中。

snvhrwxg

snvhrwxg2#

添加以下变量:

View root;
RecyclerView recyclerView;

将oncreateview更改为:

public View onCreateView(@NonNull LayoutInflater inflater,
                         ViewGroup container, Bundle savedInstanceState) {
    root = inflater.inflate(R.layout.fragment_profile, container, false);
    recyclerView = root.findViewById(R.id.recyclerView);
    return root;
}

最后-确保xml文件中的recyclerview具有以下内容:

android:id="@+id/recyclerView"
ykejflvf

ykejflvf3#

你的观点还没有膨胀,这就是为什么它找不到的原因。将代码从 onCreateonViewCreated 碎片生命周期。

@Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // your view is discoverable here
        RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    }

相关问题