嗨所以我的项目因为某些原因在模拟器上启动时出现了一个nullpointer,我不确定是什么原因。这是我得到的错误:
W/System.err: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.app.ActionBar.setBackgroundDrawable(android.graphics.drawable.Drawable)' on a null object reference
W/System.err: at com.panda.cleaner_batterysaver.ui.MainActivity.applyKitKatTranslucency(MainActivity.java:201)
W/System.err: at com.panda.cleaner_batterysaver.ui.MainActivity.onCreate(MainActivity.java:83)
代码部分:
private void applyKitKatTranslucency() {
// KitKat translucent navigation/status bar.
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
setTranslucentStatus(true);
SystemBarTintManager mTintManager = new SystemBarTintManager(this);
mTintManager.setStatusBarTintEnabled(true);
mTintManager.setNavigationBarTintEnabled(true);
// mTintManager.setTintColor(0xF00099CC);
mTintManager.setTintDrawable(UIElementsHelper
.getGeneralActionBarBackground(this));
getActionBar().setBackgroundDrawable(
UIElementsHelper.getGeneralActionBarBackground(this));
}
}
调用方法的可绘制文件:
public class UIElementsHelper {
private static final String NOW_PLAYING_COLOR = "NOW_PLAYING_COLOR";
private static final String BLUE = "BLUE";
private static final String RED = "RED";
private static final String GREEN = "GREEN";
private static final String ORANGE = "ORANGE";
private static final String PURPLE = "PURPLE";
private static final String MAGENTA = "MAGENTA";
private static final String GRAY = "GRAY";
private static final String WHITE = "WHITE";
private static final String BLACK = "BLACK";
/**
* Returns the ActionBar color based on the selected color theme (not used
* for the player).
*/
public static Drawable getGeneralActionBarBackground(Context context) {
final SharedPreferences settings = PreferenceManager
.getDefaultSharedPreferences(context);
Drawable drawable = new ColorDrawable(0xFF9acd32);
return drawable;
}
}
答案 0 :(得分:2)
在默认的styles.xml文件中,检查您使用的主题。如果您创建一个空的Activity,则默认主题是:
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
但是,您可能使用过类似的内容:
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
在这种情况下,您需要在onCreate中手动设置操作栏:
// Assuming you have a toolbar in your xml layout with id toolbar
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
ActionBar actionBar = getSupportActionBar();
if (actionBar != null) {
actionBar.setBackgroundDrawable(
UIElementsHelper.getGeneralActionBarBackground(this));
}
如果您不使用AppCompat,则需要使用getActionBar和适当的主题。