Home Ask Login Register

Developers Planet

Your answer is one click away!

Greg Peckory February 2016

RecyclerView in Fragment

I am setting up a RecyclerView inside a Fragment following the Android docs example here.

I pasted my code below, there is not much. (The only difference is I'm using a Fragment instead of an Activity).

The error I'm getting is:

java.lang.IllegalStateException: The specified child already has a parent. You must call removeView() on the child's parent first.

All solutions to this problem online are to add false argument in layout inflation for fragment. But I've already done this, and I still get the error.

My code:


mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.replace(R.id.containerView,new NewsFragment()).commit();


public class NewsFragment extends Fragment {

    private RecyclerView mRecyclerView;
    private RecyclerView.Adapter mAdapter;
    private RecyclerView.LayoutManager mLayoutManager;

    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View v =  inflater.inflate(R.layout.news_layout,container, false);

        mRecyclerView = (RecyclerView) v.findViewById(R.id.my_recycler_view);

        mLayoutManager = new LinearLayoutManager(getActivity());

        mAdapter = new NewsAdapter(new String[]{"hello","world","qwert","test","greg","peck"});

        return v;



public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
    private String[] m        


Mandeep February 2016

The error is on this line:

TextView tv = (TextView)v.findViewById(R.id.textView2);
ViewHolder vh = new ViewHolder(tv);

Change it to:

TextView tv = (TextView)v.findViewById(R.id.textView2);
ViewHolder vh = new ViewHolder(v);

The text view is already having a parent. That's why you are getting this error.

Updated code:

public class NewsAdapter extends RecyclerView.Adapter<NewsAdapter.ViewHolder> {
    private String[] mDataset;

    public static class ViewHolder extends RecyclerView.ViewHolder {
        public TextView mTextView;

        public ViewHolder(View view) {
           mTextView= (TextView)view.findViewById(R.id.textView2);

    public NewsAdapter(String[] myDataset) {
        mDataset = myDataset;

    public NewsAdapter.ViewHolder onCreateViewHolder(ViewGroup parent,
                                                   int viewType) {
        View v = LayoutInflater.from(parent.getContext())
                .inflate(R.layout.news_item, parent, false);

        ViewHolder vh = new ViewHolder(v);
        return vh;

    public void onBindViewHolder(ViewHolder holder, int position) {

    public int getItemCount() {
        return mDataset.length;

Post Status

Asked in February 2016
Viewed 3,850 times
Voted 11
Answered 1 times


Leave an answer

Quote of the day: live life