如何检测菜单按钮点击事件?

时间:2014-07-03 08:42:32

标签: android android-activity

@Override
public boolean onKeyUp(int keyCode, KeyEvent event) {
    Toast.makeText(MainTabActivity.this, "On key up ", Toast.LENGTH_LONG).show();
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        // ........
        Toast.makeText(MainTabActivity.this, "On key up ", Toast.LENGTH_LONG).show();
        return true;
    }
    return true;
}

我在Tabactivity工作,我想在菜单按钮上发生onclick事件时检测到事件。我正在使用上面的代码,但它无法正常工作

5 个答案:

答案 0 :(得分:0)

您需要覆盖onKeyDown。您正在使用onKeyUp。

@Override
public boolean onKeyDown(int keycode, KeyEvent e) 
{
    switch(keycode) 
    {
        case KeyEvent.KEYCODE_MENU:
            doSomething();
            return true;
    }

    return super.onKeyDown(keycode, e);
}

答案 1 :(得分:0)

public boolean onKeyDown(int keyCode, KeyEvent event) { 
    if (keyCode == KeyEvent.KEYCODE_MENU) {
        Toast.makeText(this, "On key up ", Toast.LENGTH_LONG).show();
        return true;
    }
    return super.onKeyDown(keyCode, event); 
} 

尝试使用此代码,对我而言

答案 2 :(得分:0)

您忘记致电super来电onKeyDown活动 -

public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_MENU) {
            return true;
        }
        return super.onKeyDown(keyCode, event);
    }

答案 3 :(得分:0)

使用onKeyDown检测按钮点击事件。

public boolean onKeyDown(int keyCode, KeyEvent event) {        
     if (keyCode == KeyEvent.KEYCODE_MENU) {         
        //do your work      
        return true;      
    }       
    return super.onKeyDown(keyCode, event);   
} 

答案 4 :(得分:0)

尝试下面的代码,它的工作原理...

InnerRecevierM innerReceiver;
IntentFilter intentFilter;

@Override
    protected void onCreate(Bundle savedInstanceState) {
    ...
    innerReceiver = new InnerRecevierM();
        intentFilter = new IntentFilter(Intent.ACTION_CLOSE_SYSTEM_DIALOGS);
        registerReceiver(innerReceiver, intentFilter);
}

class InnerRecevierM extends BroadcastReceiver {

        final String SYSTEM_DIALOG_REASON_KEY = "reason";
        final String SYSTEM_DIALOG_REASON_MENU_KEY = "recentapps";

        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();

            if (Intent.ACTION_CLOSE_SYSTEM_DIALOGS.equals(action)) {
                String reason = intent.getStringExtra(SYSTEM_DIALOG_REASON_KEY);

                if (reason != null) {
                    if (reason.equals(SYSTEM_DIALOG_REASON_MENU_KEY)) {
                        Toast.makeText(MainActivity.this, "Menu Button Pressed", Toast.LENGTH_SHORT).show();
                    }
                }
            }
        }
    }

@Override
protected void onDestroy() {
    super.onDestroy();
    if(innerReceiver != null) {
        unregisterReceiver(innerReceiver);
                innerReceiver = null;
    }
    }