【问题标题】:Add a button to the top right of action bar在操作栏的右上角添加一个按钮
【发布时间】:2015-07-13 15:08:30
【问题描述】:

有没有办法可以在ActionBar 的右上角添加一个按钮,例如默认设置Button 的位置?我删除了设置Button,但我想在其位置添加自定义Button

【问题讨论】:

    标签: android android-actionbar android-button


    【解决方案1】:

    您可以通过编辑/创建菜单 xml 文件来添加按钮:

    <?xml version="1.0" encoding="utf-8"?>
    <menu xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:app="http://schemas.android.com/apk/res-auto">
    
        <item
            android:id="@+id/action_name"
            android:icon="@drawable/you_resource_here"
            android:title="Text to be seen by user"
            app:showAsAction="always"
            android:orderInCategory="0"/>
    
    </menu>
    

    然后在您的活动中,如果您创建了一个新文件,您需要编辑onCreateOptionsMenu

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.menu_main, menu);
        return true;
    }
    

    您可以通过以下方法编辑操作的作用:

    @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();
    
        //noinspection SimplifiableIfStatement
        if (id == R.id.action_name) {
            return true;
        }
    
        return super.onOptionsItemSelected(item);
    }
    

    【讨论】:

    • 谢谢!我会尝试一下然后返回
    • 抱歉,我知道这已经晚了,但是由于某种原因,当我单击按钮时没有任何反应。我还需要添加其他代码吗?
    • 如果您看到图标出现在 ActionBar 中,那么单击它应该可以按照上面的说明进行操作。尝试在 onOptionsItemSelected 的第一行添加 Toast/log 行,问题可能出在其他地方。
    【解决方案2】:

    这可能更容易,但我使用工具栏代替:

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        switch(item.getItemId()) {
            case R.id.action_name:
                //your code
                break;
        }
        return super.onOptionsItemSelected(item);
    }
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2022-01-04
      相关资源
      最近更新 更多