[英]Android Studio: NullPointerException with getSupportActionBar()
我想在我的活動中顯示一個 ActionBar,同時只顯示一個結束符號。 因此我使用了 getSupportActionBar() 方法:
getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_close);
setTitle("Add Event");
但它拋出一個 NullPointerExeption 因為顯然沒有 ActionBar 調用:
java.lang.RuntimeException: Unable to start activity ComponentInfo{com.example.tutorial/com.example.tutorial.AddEventActivity}: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.appcompat.app.ActionBar.setHomeAsUpIndicator(int)' on a null object reference
在我的 MainActivity 中,我實現了一個抽屜導航,我已經使用了一個有效的工具欄:
public class MainActivity extends AppCompatActivity {
protected DrawerLayout mDrawer;
private Toolbar toolbar;
private NavigationView nvDrawer;
// Make sure to be using androidx.appcompat.app.ActionBarDrawerToggle version.
private ActionBarDrawerToggle drawerToggle;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
// Set a Toolbar to replace the ActionBar.
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
// This will display an Up icon (<-), we will replace it with hamburger later
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
// Find our drawer view
mDrawer = (DrawerLayout) findViewById(R.id.drawer_layout);
drawerToggle = setupDrawerToggle();
// Setup toggle to display hamburger icon with nice animation
drawerToggle.setDrawerIndicatorEnabled(true);
drawerToggle.syncState();
// Tie DrawerLayout events to the ActionBarToggle
mDrawer.addDrawerListener(drawerToggle);
// Find our drawer view
nvDrawer = (NavigationView) findViewById(R.id.nvView);
// Setup drawer view
setupDrawerContent(nvDrawer);
}
我該如何解決? 提前致謝!
替換這一行:
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
這條線:
ActionBar actionBar = getSupportActionBar();
actionBar.setDisplayHomeAsUpEnabled(true);
這應該可以解決您的問題。
您可以嘗試將以下屬性添加到您的ActivityManifest.xml
下的MainActivity
項
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
然后嘗試使用getSupportActionBar()
訪問它。 通過這種方式,您可以使用相關主題選擇您不想或不想包含操作欄的活動。 例如:
<activity
android:name=".SecondActivity"
android:theme="@style/Theme.AppCompat.Light.DarkActionBar"
android:parentActivityName=".MainActivity" />
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.