当与MaterialNavigationDrawer库一起使用时,RecyclerView提供Null对象参考

时间:2015-04-20 01:16:10

标签: android navigation-drawer android-recyclerview

我正在尝试使用MaterialNavigationDrawer库。维基说:

MaterialNavigationDrawer是一个ActionBarActivity,但有一些重要的变化:

  • 你有一个init方法
  • 您不得覆盖onCreate方法
  • 你不能调用setContentView方法,因为库有它自己的布局
  • 你不能覆盖onBackPressed方法,因为库自己实现它

所以我使用了这段代码并删除了onCreate方法代码。我把RecyclerView初始化代码放在init函数中(我之前在onCreate中做过)。

public class MainActivity extends MaterialNavigationDrawer implements
        OffersFragment.OnEnterNameFragmentInteractionListener,
        OfferDetailsFragment.OnShowNamesFragmentInteractionListener {

    public static final String TAG = "MainActivity";

    RecyclerView recyclerView;
    LinearLayoutManager linearLayoutManager;

    @Override
    public void init(Bundle bundle) {
        loadSampleData();

        recyclerView = (RecyclerView) findViewById(R.id.rv_offers);
        recyclerView.setHasFixedSize(true);

        linearLayoutManager = new LinearLayoutManager(getApplicationContext());
        recyclerView.setLayoutManager(linearLayoutManager);

        RecyclerViewAdapter rvAdapter = new RecyclerViewAdapter(this, offerList);
        recyclerView.setAdapter(rvAdapter);


        MaterialAccount account = new MaterialAccount(this.getResources(),
                "Akshay","akshay.thapa23@gmail.com",R.drawable.photo, R.drawable.navbar_header);
        account.setTitle("Title");
        this.addAccount(account);

        MaterialSection section = newSection("Share", R.drawable.ic_share_grey600_24dp, new OffersFragment());
        this.addSection(section);

        MaterialSection settingsSection = newSection("Settings", new OffersFragment());
        this.addBottomSection(settingsSection);
    }
....
....
}

但是这给了我以下错误,我想那不是我应该怎么做的。有人可以帮忙吗?

尝试调用虚方法'void android.support.v7.widget.RecyclerView $ LayoutManager.onMeasure(android.support.v7.widget.RecyclerView $ Recycler,android.support.v7.widget.RecyclerView $ State,int, int)'对空对象引用             在android.support.v7.widget.RecyclerView.onMeasure(RecyclerView.java:1764)

2 个答案:

答案 0 :(得分:1)

我能够通过引用this来使其工作。我现在不是在父活动中初始化回收器视图,而是在Fragment本身中进行,它可以工作。

答案 1 :(得分:0)

尝试仅使用活动上下文linearLayoutManager = new LinearLayoutManager(this);