Using CardView and RecyclerView in my layout files throws an exception

前端 未结 4 1264
[愿得一人]
[愿得一人] 2021-02-13 20:06

So I\'ve been taking a shot at the Material Design of Android Preview L. I imported both the CardView and the RecyclerView libraries.

I use the

相关标签:
4条回答
  • 2021-02-13 20:50

    I am using Eclipse and faced the same issue. As suggested by user7610, you need to call recyclerView.setLayoutManager() to get over this.

    Here is how i solved it..

    Create a member variable..

    RecyclerView.LayoutManager mLayoutManager;
    

    In onCreate() or onCreateView()

    recyclerView = (RecyclerView) view
                    .findViewById(R.id.business_recycler_view);
    recyclerView.setHasFixedSize(true);
    
    mLayoutManager = new LinearLayoutManager(getActivity());
    recyclerView.setLayoutManager(mLayoutManager);
    

    This solved my NullPointerException.

    0 讨论(0)
  • 2021-02-13 20:53

    I found Similar Issue. As such if we only inflate layout which consist RecyclerView then While doing setcontentView it gives error because layout manager is not set for Recyclerview Defined in Layout file.

    RecyclerView recyclerView = (RecyclerView) findViewById(R.id.searchResultsList);
    LinearLayoutManager layoutmanager = new LinearLayoutManager(this);
    layoutmanager.setOrientation(LinearLayoutManager.VERTICAL);
    recyclerView.setLayoutManager(layoutmanager);
    
    0 讨论(0)
  • 2021-02-13 21:03

    If some one is facing the same issue for Recycler view inside fragment use this code

    @Override
        public View onCreateView(LayoutInflater inflater, ViewGroup container,
                                 Bundle savedInstanceState) {
            // Inflate the layout for this fragment
            View rootView = inflater.inflate(R.layout.fragment_timeline, container, false);
    
            mRecyclerView = (RecyclerView) rootView.findViewById(R.id.my_recycler_view);
    
            // use this setting to improve performance if you know that changes
            // in content do not change the layout size of the RecyclerView
    
            mRecyclerView.setHasFixedSize(true);
            // use a linear layout manager
            mLayoutManager = new LinearLayoutManager(getActivity());
            mRecyclerView.setLayoutManager(mLayoutManager);
    
    
            String[] abc = {"hi","how are you","this is recycler"};
            // specify an adapter (see also next example)
            mAdapter = new RecyclerViewAdapter(abc);
            mRecyclerView.setAdapter(mAdapter);
            return rootView;
        }
    
    0 讨论(0)
  • 2021-02-13 21:05

    This is a bug in Android Studio. The preview tool does not know how do initialize the widgets. I believe so, because the same exception is thrown from your app if you forget to call recyclerView.setLayoutManager() in your code.

    0 讨论(0)
提交回复
热议问题