方法调用' setDisplayHomeAsUpEnabled'可能会产生&java; Lang.lang.NullPointerException

时间:2016-12-11 16:40:42

标签: android

为什么这行会产生NullPointerException?

getSupportActionBar().setDisplayHomeAsUpEnabled(true);

我已导入android.support.v7.app.AppCompatActivity 在build.grade我正在使用com.android.support.design:25.0.1

public class PhotosActivity extends AppCompatActivity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.photos_activity);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        int id = item.getItemId();

        if (id == android.R.id.home) {
            // finish the activity
            onBackPressed();
            return true;
        }

        return super.onOptionsItemSelected(item);
    }
}

错误:http://pastebin.com/aCQ4Hvpi

1 个答案:

答案 0 :(得分:15)

此条件将修复该警告:

if (getSupportActionBar() != null) {

这就是我设置SupportActionBar的方法,也许这会有所帮助!

Toolbar myToolbar = (Toolbar) findViewById(R.id.toolbar_top);
    setSupportActionBar(myToolbar);
    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setLogo(R.mipmap.ic_launcher);
        getSupportActionBar().setDisplayUseLogoEnabled(true);
    }