android - 如何在其 setSupportActionBar 时在操作栏中添加图标

标签 android

我有以下设置工具栏的代码

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);
   list = (ListView) findViewById(R.id.ListView);
    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    getSupportActionBar().setDisplayHomeAsUpEnabled(true);

    viewPager = (ViewPager) findViewById(R.id.viewpager);
    setupViewPager(viewPager);

    tabLayout = (TabLayout) findViewById(R.id.tabs);
    tabLayout.setupWithViewPager(viewPager);
    //downloadImage();
}

我应该添加这段代码吗?

@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.main, menu);

我想在工具栏操作栏中有图标怎么办?

最佳答案

是的,你应该添加

   @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.main, menu);
        return true;
    }
 //and this to handle actions
    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        // Handle action bar item clicks here. The action bar will
        // automatically handle clicks on the Home/Up button, so long
        // as you specify a parent activity in AndroidManifest.xml.
        int id = item.getItemId();
        if (id == R.id.action_settings) {
            return true;
        }
        return super.onOptionsItemSelected(item);
    }

要添加图标,到menu目录下的main.xml中添加

<item android:id="@+id/action_settings" 
        android:title="@string/action_settings"
        android:icon="@drawable/icon"
        android:orderInCategory="100" 
        app:showAsAction="always" />

关于android - 如何在其 setSupportActionBar 时在操作栏中添加图标,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33328486/

相关文章:

android - 在 Android Studio 中读取文件 modules.xml 失败

java - List<Trail> 无法转换为 Context

java - MediaStore.Images.Media.insertImage 在某些设备中返回 null

android - 在 Android 中更改 ActionMode 背景颜色时遇到问题

android - 在 WebView 中禁用邮寄地址的自动链接

android - 在现有 ListVIew 中添加更多项目时 ImageView 重叠

android - WebView检测按钮点击事件

android - 自定义 Facebook 登录按钮

android - Flutter CupertinoTimerPicker不适合父级宽度或高度

android - 在 TextInputLayout 里面切换