DrawerLayout使用问题 哪里有问题 点击图片后停止运行并报错 5C

错误
java.lang.NullPointerException: Attempt to invoke virtual method 'void android.support.v4.widget.DrawerLayout.openDrawer(android.view.View)' on a null object reference
at com.cy.mynj.com.cy.mynj.activities.MainActivity.onClick(MainActivity.java:57)
at android.view.View.performClick(View.java:4848)
at android.view.View$PerformClick.run(View.java:20300)
at android.os.Handler.handleCallback(Handler.java:815)
at android.os.Handler.dispatchMessage(Handler.java:104)
at android.os.Looper.loop(Looper.java:194)
at android.app.ActivityThread.main(ActivityThread.java:5682)
at java.lang.reflect.Method.invoke(Native Method)
at java.lang.reflect.Method.invoke(Method.java:372)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:963)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:758)

public class MainActivity extends AppCompatActivity implements View.OnClickListener{
//左边栏
private List mList = new ArrayList();
private ListView mListView;
DrawerLayout mDrawerLayout;
//
private ImageView iv_left;

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
    initData();
    initViews();
}

private void initData() {
    mList.add(new ContentModel(R.drawable.weather_icons, "天气", 1));
    mList.add(new ContentModel(R.drawable.scenic_spot_icon, "本地美景", 2));
    mList.add(new ContentModel(R.drawable.bus_icon, "交通", 3));
    mList.add(new ContentModel(R.drawable.security_icon, "社保", 4));
    mList.add(new ContentModel(R.drawable.insurance_icon, "医疗", 5));
    mList.add(new ContentModel(R.drawable.ciziten_card_icon, "市民卡", 6));
    mList.add(new ContentModel(R.drawable.employ_icon, "招聘", 7));
    mList.add(new ContentModel(R.drawable.news_icon, "新闻", 8));
}
private void initViews(){
    mListView = (ListView) findViewById(R.id.left_listview);
    ContentAdapter adapter = new ContentAdapter(this,mList);
    mListView.setAdapter(adapter);

    iv_left = (ImageView)findViewById(R.id.leftmenu);
    iv_left.setOnClickListener(this);

}

@Override
public void onClick(View view) {
    switch (view.getId()){
        case R.id.leftmenu:
            **mDrawerLayout.openDrawer(Gravity.LEFT);**
            break;
        default:
            break;
    }
}

}

8个回答

在initViews里面初始化mDrawerLayout = findViewById()

要这样写drawerLayout.openDrawer(drawerContent);,你的布局里面必须有一个drawerContent,而且这个drawerContent只能有一层包裹

mDrawerLayout没有初始化findViewById

*mDrawerLayout.openDrawer(Gravity.LEFT);

这个东西没有初始化

检查下代码的57行
我粗略观察你的代码,应该是你没有初始化listview就直接mList.add了,你检查下是不是

private ListView mListView;

mList.add();

mDrawerLayout 这个没有赋值,是空的

mDrawerLayout 貌似没有 findViewById的操作

at com.cy.mynj.com.cy.mynj.activities.MainActivity.onClick(MainActivity.java:57)看看你的代码的57行,如果没错的,应该是没有初始化

Csdn user default icon
上传中...
上传图片
插入图片
抄袭、复制答案,以达到刷声望分或其他目的的行为,在CSDN问答是严格禁止的,一经发现立刻封号。是时候展现真正的技术了!
立即提问