开发者

Dispatch keyDown to TabActivity

In my application I have 4 tabs in my TabActivity I want a user confirmation dialog popup when user exits my application.

I have overridden the onKeyDown event of TabActivity and coded my requirements but the result is not as expected i.e. no popup comes when user exits, but when I am overriding on key down of my child tabs the requirement is full filled.

Yes I can simply copy paste the onKeyDown code for all my child tabs, but is there a best practice for this, may be I can dispatch the onKeyDown to my TabActivity.

Heres the code:

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
    if(keyCode == KeyEvent.KEYCOD开发者_如何转开发E_BACK) {
        new AlertDialog.Builder(this)
        .setTitle("Confirm Quit")
        .setMessage("Really Quit ?")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }

        })
        .setNegativeButton("Wait!", null)
        .show();

        return true;
    }
    else {
        return super.onKeyDown(keyCode, event);
    }

}


You must override onBackPressed() method.

@Override
public void onBackPressed() {
new AlertDialog.Builder(this)
        .setTitle("Confirm Quit")
        .setMessage("Really Quit ?")
        .setPositiveButton("OK", new DialogInterface.OnClickListener() {

            @Override
            public void onClick(DialogInterface dialog, int which) {

            }

        })
        .setNegativeButton("Wait!", null)
        .show();
return;
}

EDIT: Seems that you use 1.6 where there is no onBackPressed

I think that you must override onKeyUp(...) like in this sample.


This is how I achieved it

In my TabActivity I created a static method to handle my all calls from child Tabs

public static boolean hanndleChildBackButtonPress(final Activity activity,int keyCode, KeyEvent event){

    if(keyCode == KeyEvent.KEYCODE_BACK) {
            //HANDLING MY ON KEY DOWN LOGIC
            return true;
    }
    else {
            return false;
    }

}

And in my Child Tabs I diverted KeyDown call to static method from TabActivity

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
     if(MyTabActivity.hanndleChildBackButtonPress(this, keyCode, event)) {
            return true;
        }
        else {
            return super.onKeyDown(keyCode, event);
        }

}


You can just override the onKeyDown method in the subactivities of the Tabactivity like following, to avoid the KeyEvent.KEYCODE_BACK is consumed by the subactivities.

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
            return false;
        } else {
            return super.onKeyDown(keyCode, event);
    }
}
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜