使用 getSupportActionBar() 的简单操作栏 - 添加主页<和设置图标



我想知道是否可以简单地添加一行代码将设置图标添加到我的操作栏中。我有几个页面只有一个简单的后退按钮,但想在栏中添加另一个按钮。可能吗?还是我需要完成菜单项工具栏等的整个过程?这是代码

使用 AppCompatActivity

创建时:

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
            if (id == android.R.id.home) {
        finish();
    }
    return super.onOptionsItemSelected(item);
}

只是试图简化事情。我之前已经制作了自定义工具栏,您将在其中加载工具栏和菜单项。但只是想知道您是否可以通过这个做到这一点,因为我只想要一个额外的按钮:)

是的,这是可能的。

首先,您需要创建一个设置.xml

<item
android:id="@+id/setting"
android:title="@string/menu_setting_label"
android:icon="@drawable/setting"
android:showAsAction="always"
/>

然后覆盖您的onCreateOptionsMenuonOptionsItemSelected

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.setting, menu);
    return true;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.setting:
              .... // your code
            break;
    }
    return super.onOptionsItemSelected(item);
}

相关内容

最新更新