android实现始终显示overflow菜单的方法

在Android程序设计中,通常来说在Actionbar中在条目过多时会显示三个竖着的小点的菜单,但在实机测试的时候发现并不显示,查找资料并测试之后发现问题所在:如果该机器拥有实体的menu键则不在右侧显示溢出菜单,而改为按menu来生成。这样就不利于统一的界面风格。

我们可以改变系统探测实体menu键的存在与否来改变这个的显示。

菜单显示是根据public boolean hasPermanentMenuKey ()这个方法来判断的。这个方法是获取sHasPermanentMenuKey的boolean值。

解决方法如下:

在onCreate()中加入:


       super.onCreate(savedInstanceState);
        makeActionOverflowMenuShown();
        setContentView(R.layout.activity_android);

    /**
     * 有的手机不显示菜单栏
     */
    private void makeActionOverflowMenuShown() {
        //devices with hardware menu button (e.g. Samsung Note) don't show action overflow menu
        try {
            ViewConfiguration config = ViewConfiguration.get(this);
            Field menuKeyField = ViewConfiguration.class.getDeclaredField("sHasPermanentMenuKey");
            if (menuKeyField != null) {
                menuKeyField.setAccessible(true);
                menuKeyField.setBoolean(config, false);
            }
        } catch (Exception e) {

        }
    }


猜你喜欢

转载自blog.csdn.net/mp624183768/article/details/80247287