在Fragment中显示RecyclerView

时间:2014-10-29 00:51:05

标签: java android android-fragments android-5.0-lollipop android-recyclerview

我在Android Lollipop中尝试了新的RecyclerView而且我被卡住了。

我试图在TextView内部接收一个带有图标和图标右侧Fragment的列表。

I found this great tutorial了解如何设置RecyclerView。我遵循了每一点,只改变了item_layout.xml以满足我的需求。

项目构建没有任何错误,但是当它在我的设备上启动时,我收到此错误:

  

java.lang.RuntimeException:无法启动活动ComponentInfo {com.fredrikaldgard.materialcolors / com.fredrikaldgard.materialcolors.MainActivity}:java.lang.NullPointerException:尝试调用虚方法' void android.support。 v7.widget.RecyclerView.setLayoutManager(android.support.v7.widget.RecyclerView $布局管理)'在空对象引用上

我试图解决这个问题,但我在Android开发方面非常业余。

这是我的MainActivity

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // 1. get a reference to recyclerView
    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list);

    // 2. set layoutManger
    recyclerView.setLayoutManager(new LinearLayoutManager(this));

    // this is data fro recycler view
    ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle),
            new ItemData("Red",R.drawable.color_ic_launcher),
            new ItemData("Blue",R.drawable.indigo),
            new ItemData("Green",R.drawable.circle),
            new ItemData("Amber",R.drawable.color_ic_launcher),
            new ItemData("Deep Orange",R.drawable.indigo)};


    // 3. create an adapter
    MyAdapter mAdapter = new MyAdapter(itemsData);
    // 4. set adapter
    recyclerView.setAdapter(mAdapter);
    // 5. set item animator to DefaultAnimator
    recyclerView.setItemAnimator(new DefaultItemAnimator());

我的MyAdapter

public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
private ItemData[] itemsData;

public MyAdapter(ItemData[] itemsData) {
    this.itemsData = itemsData;
}

// Create new views (invoked by the layout manager)
@Override
public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                               int viewType) {
    // create a new view
    View itemLayoutView = LayoutInflater.from(parent.getContext())
            .inflate(R.layout.item_layout, null);

    // create ViewHolder

    ViewHolder viewHolder = new ViewHolder(itemLayoutView);
    return viewHolder;
}

// Replace the contents of a view (invoked by the layout manager)
@Override
public void onBindViewHolder(ViewHolder viewHolder, int position) {

    // - get data from your itemsData at this position
    // - replace the contents of the view with that itemsData

    viewHolder.txtViewTitle.setText(itemsData[position].getTitle());
    viewHolder.imgViewIcon.setImageResource(itemsData[position].getImageUrl());


}

// inner class to hold a reference to each item of RecyclerView
public static class ViewHolder extends RecyclerView.ViewHolder {

    public TextView txtViewTitle;
    public ImageView imgViewIcon;

    public ViewHolder(View itemLayoutView) {
        super(itemLayoutView);
        txtViewTitle = (TextView) itemLayoutView.findViewById(R.id.item_title);
        imgViewIcon = (ImageView) itemLayoutView.findViewById(R.id.item_icon);
    }
}


// Return the size of your itemsData (invoked by the layout manager)
@Override
public int getItemCount() {
    return itemsData.length;
}
}

修改:此处为Fragment

public class ColorsFragment extends Fragment {

    public ColorsFragment(){}

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

        View rootView = inflater.inflate(R.layout.fragment_colors, container, false);

        return rootView;
    }
}

可能出了什么问题?

4 个答案:

答案 0 :(得分:44)

这是前段时间的问题,但基于@ nacho_zona3提供的答案以及之前的片段经验,问题是当您尝试使用{{{{{ 1}} findViewById()中的方法来修复此问题,请移动以下代码:

onCreate()

到你的片段// 1. get a reference to recyclerView RecyclerView recyclerView = (RecyclerView) findViewById(R.id.list); // 2. set layoutManger recyclerView.setLayoutManager(new LinearLayoutManager(this)); // this is data fro recycler view ItemData itemsData[] = { new ItemData("Indigo",R.drawable.circle), new ItemData("Red",R.drawable.color_ic_launcher), new ItemData("Blue",R.drawable.indigo), new ItemData("Green",R.drawable.circle), new ItemData("Amber",R.drawable.color_ic_launcher), new ItemData("Deep Orange",R.drawable.indigo)}; // 3. create an adapter MyAdapter mAdapter = new MyAdapter(itemsData); // 4. set adapter recyclerView.setAdapter(mAdapter); // 5. set item animator to DefaultAnimator recyclerView.setItemAnimator(new DefaultItemAnimator()); 电话。需要进行少量重构,因为从此方法调用的所有变量和方法都必须是静态的。最终代码应如下所示:

onCreateView()

所以这里最重要的是,无论你拨打 public class ColorsFragment extends Fragment { public ColorsFragment() {} @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { View rootView = inflater.inflate(R.layout.fragment_colors, container, false); // 1. get a reference to recyclerView RecyclerView recyclerView = (RecyclerView) rootView.findViewById(R.id.list); // 2. set layoutManger recyclerView.setLayoutManager(new LinearLayoutManager(getActivity())); // this is data fro recycler view ItemData itemsData[] = { new ItemData("Indigo", R.drawable.circle), new ItemData("Red", R.drawable.color_ic_launcher), new ItemData("Blue", R.drawable.indigo), new ItemData("Green", R.drawable.circle), new ItemData("Amber", R.drawable.color_ic_launcher), new ItemData("Deep Orange", R.drawable.indigo) }; // 3. create an adapter MyAdapter mAdapter = new MyAdapter(itemsData); // 4. set adapter recyclerView.setAdapter(mAdapter); // 5. set item animator to DefaultAnimator recyclerView.setItemAnimator(new DefaultItemAnimator()); return rootView; } } 的任何地方,都需要使用findViewById()

答案 1 :(得分:26)

使用该视图对核心视图进行充气后,您应该在RecyclerView中检索Fragment。也许它无法找到您的回收商,因为它不属于活动

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
    final View view = inflater.inflate(R.layout.fragment_artist_tracks, container, false);
    final FragmentActivity c = getActivity();
    final RecyclerView recyclerView = (RecyclerView) view.findViewById(R.id.recyclerView);
    LinearLayoutManager layoutManager = new LinearLayoutManager(c);
    recyclerView.setLayoutManager(layoutManager);

    new Thread(new Runnable() {
        @Override
        public void run() {
            final RecyclerAdapter adapter = new RecyclerAdapter(c);
            c.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    recyclerView.setAdapter(adapter);
                }
            });
        }
    }).start();

    return view;
}

答案 2 :(得分:0)

确保您具有正确的布局,并且RecyclerView ID位于布局内。否则,您将收到此错误。我遇到了同样的问题,然后我发现布局错误。

    public class ColorsFragment extends Fragment {

         public ColorsFragment() {}

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

==> make sure you are getting the correct layout here. R.layout...

             View rootView = inflater.inflate(R.layout.fragment_colors, container, false); 

答案 3 :(得分:0)

我遇到了同样的问题。当我使用此代码调用上下文时,得到了解决方案。我使用网格布局。如果您使用另一个,则可以更改。

   recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),1));

如果要设置适配器。因此,您可以按照此操作。只需调用getContext

  adapter = new Adapter(getContext(), myModelList);

如果要展示敬酒,请在上方使用相同的内容

   Toast.makeText(getContext(), "Error in "+e, Toast.LENGTH_SHORT).show();

希望这会起作用。

快乐编码