user3432681 user3432681 - 2 months ago 8
Android Question

Implement a RecyclerView in a Fragment

I trying to create a

ListView
in a
Fragment
within a
ViewPager
in a
AppCompatActivity
. In the
AppCompatActivity
are all view elements are wrappend in a
CoordinatorLayout
. Because I used the
CoordinatorLayout
. I have to use a
RecylerView
I am trying to follow the training from
developer.android.com, but my application stopped after my log. This is my code in myFragment where the applications stopped.

import android.app.Activity;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

//...

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_city_list, container, false)

mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
mLayoutManager = new LinearLayoutManager(this.getActivity());
Log.d("debugMode", "The application stopped after this");
mRecyclerView.setLayoutManager(mLayoutManager);

mAdapter = new RecyclerAdapter(getNames());
mRecyclerView.setAdapter(mAdapter);
return view;
}

//...

Answer

Use this

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_city_list, container, false)

    // Replace 'android.R.id.list' with the 'id' of your RecyclerView
    mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);
    mLayoutManager = new LinearLayoutManager(this.getActivity());
    Log.d("debugMode", "The application stopped after this");
    mRecyclerView.setLayoutManager(mLayoutManager);

    mAdapter = new RecyclerAdapter(getNames());
    mRecyclerView.setAdapter(mAdapter);
    return view;
}

You should call the setLayoutManager & setAdapter methods (respectively) on the Recyclerview.

Plus,

mRecyclerView = (RecyclerView) view.findViewById(android.R.id.list);

you should not use android.R.id.list, as you're not using a ListFragment. Replace it with the id of you Recyclerview (as in your XML layout).