在设置 actionBar 图标时获取 null

Getting null at setting actionBar icon

我的 actionBar 有问题。尝试设置图标但仍然为空:/这是代码:

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        getActionBar().setIcon(R.drawable.logo);
        getActionBar().setBackgroundDrawable(new ColorDrawable(Color.parseColor("#51717e")));

    }

Ofc 我的可绘制文件夹中有徽标。这两行都不正确 - 图标和背景颜色。帮助:/

您需要在 ActionBarActivity 上调用 getSupportActionBar()。不要调用 getActionBar()——它在旧设备上不可用,对于新的 r21 版本的 appcompat-v7,我希望它一直为 return null,因为新的 ActionBarActivity 禁用并替换了系统操作 bar.and 在 try catch 中包围这两行,例如:

try{
getSupportActionBar().setIcon(R.drawable.logo);
 getSupportActionBar() .setBackgroundDrawable(new ColorDrawable(Color.parseColor("#51717e")));
 }catch(NullPointerException e)
 {
 e.printstacktrace();
 }

试试这个:

    getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
    setContentView(R.layout.activity_main);
    ActionBar actionBar = getActionBar();

你得到的 Actionbar 是空的,因为主题没有 ActionBar。 尝试在 styles.xml

中设置背景和图标