开发者社区> 问答> 正文

关于Android Action Bar 上的 Switch控件

因为要在Action Bar 上弄个 Switch 按钮,所以我照
http://stackoverflow.com/questions/12107031/how-to-add-a-switch-to-android-action-bar
的方法做了个.
现在做到按钮了,但却不能使用onCheckedChanged来验测按钮的开启我该怎样做?
这是我实现Action Bar 上 放Switch 的代码
mainmenu.xml
screenshot
menurelaty.xml
screenshot
我在想:会不会是因为MainActivity上的setContentView是main_activity.xml而不是实现Switch的menurelaty.xml才不能以findViewByid然后.onCheckedChanged 来验测按钮的开启

展开
收起
蛮大人123 2016-02-27 15:33:18 2827 0
1 条回答
写回答
取消 提交回答
  • 我说我不帅他们就打我,还说我虚伪

    我也是参考这个来的,同样监听不到switch的onchangelistener
    不过可以在onCreateOptionsMenu中监听即可
    [java]
    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.order, menu);

    Switch switchShop=(Switch) menu.findItem(R.id.action_test_switch_shop).getActionView().findViewById(R.id.switchForActionBar);
    switchShop.setOnCheckedChangeListener(new OnCheckedChangeListener() {
    
        @Override
        public void onCheckedChanged(CompoundButton btn, boolean isChecked) {
            if (isChecked) { //开店申请
                UI.toast(getApplicationContext(), "开店啦");
            } else { //关店申请
                UI.toast(getApplicationContext(), "关店啦");
            }
        }
    });
    return true;

    }
    [/java]

    2019-07-17 18:48:56
    赞同 展开评论 打赏
问答排行榜
最热
最新

相关电子书

更多
58同城Android客户端Walle框架演进与实践之路 立即下载
Android组件化实现 立即下载
蚂蚁聚宝Android秒级编译——Freeline 立即下载