简体   繁体   English

按下后退按钮时如何创建警报对话框?

[英]How to create a alert dialog box when back button is pressed?

I want to show a alert dialog box to the user when the back button is pressed..For example :Are you sure want to exit ?.I am not having a problem in creating a alert dialog box..I am having a problem in where to call this dialog box method(). 我想在按下后退按钮时向用户显示一个警报对话框。.例如:确定要退出吗?创建警报对话框时没有问题。在何处调用此对话框method()。

This is my HomeScreen.java 这是我的HomeScreen.java

public class HomeScreen extends TabActivity {
    ConferenceOpenHelper helper_ob;
    Cursor cursorHome;
    ProfileEditScreen profileEditScreen;
    ConferenceAdapter adapter;
    EcMeeting meeting;
    final Context context = this;
    public static int HOMETEMP = 1;// Constant for Deleting the last created id
// in edit profile screen (Cancel)
    public static String HOME = "home";// constant for updating status column
    public static String CUSTOM_DIALER = "custom";
    public static String TEMPLATE = "template";// constant for updating status              // column   
    public static TabHost tabHost;
    public static final int QUICK_START = 1;// Constant for menu options
    public static final int TEMPLATE_SCREEN = 2;// Constant for menu options
    public static final int USER_GUIDE = 3;// Constant for menu options
    public static final int QUICK_CALL = 4;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState); 

        setContentView(R.layout.tab);        
        Resources ressources = getResources();      
         tabHost = getTabHost();        
        // Android tab
         Intent photo = new Intent().setClass(this,EcMeeting.class);
            TabSpec tabSpecphoto = tabHost
              .newTabSpec("Calendar")
              .setIndicator("Calendar", ressources.getDrawable(R.drawable.calendartab))
              .setContent(photo);
        // Apple tab
        Intent intentApple = new Intent().setClass(this,CallListScreen.class);
        TabSpec tabSpecApple = tabHost
          .newTabSpec("Calls")
          .setIndicator("Calls", ressources.getDrawable(R.drawable.ic_action_device_access_call))
          .setContent(intentApple);

        // Windows tab
        Intent intentWindows = new Intent().setClass(this,UserSettingActivity.class);
        TabSpec tabSpecWindows = tabHost
          .newTabSpec("Settings")
          .setIndicator("Settings", ressources.getDrawable(R.drawable.ic_action_setting))
          .setContent(intentWindows); 

        // add all tabs 
        tabHost.addTab(tabSpecphoto);
        tabHost.addTab(tabSpecApple);
        tabHost.addTab(tabSpecWindows);

        //set Windows tab as default (zero based)
        /*tabHost.setCurrentTab(0);*/

         for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
            {
                tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#d3d3d3"));
            }
            tabHost.getTabWidget().setCurrentTab(0);
            /*tabHost.getTabWidget().getChildAt(0).setBackgroundColor(Color.parseColor("#C35817"));*/
         }
    public boolean onCreateOptionsMenu(Menu menu) {
        super.onCreateOptionsMenu(menu);
        menu.add(0, QUICK_START, 0, "Quick Start").setIcon(R.drawable.ic_menu_add_icon);        
        menu.add(0, USER_GUIDE, 0, "User Guide").setIcon(R.drawable.ic_menu_guide_icon);

        return true;
    }

    @Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
               .setMessage("Are you sure you want to exit?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        HomeScreen.this.finish();
                   }
               })
               .setNegativeButton("No", null)
               .show();
    }







    @Override
    public boolean onOptionsItemSelected(MenuItem item) {
        super.onOptionsItemSelected(item);
        switch (item.getItemId()) {
        case QUICK_START:
            startActivity(new Intent(this, ConfDialerScreen.class));
            break;

        case USER_GUIDE:
            startActivity(new Intent(this, UserGuideScreen.class));
            break;
        }
        return true;
    }
        public void onTabChanged(String tabId) {
            // TODO Auto-generated method stub
            for(int i=0;i<tabHost.getTabWidget().getChildCount();i++)
            {
                tabHost.getTabWidget().getChildAt(i).setBackgroundColor(Color.parseColor("#8A4117"));
            }

            tabHost.getTabWidget().getChildAt(tabHost.getCurrentTab()).setBackgroundColor(Color.parseColor("#C35817"));     
    }   
}

This is the method() to create alert dialog 这是创建警报对话框的method()

@Override
    public void onBackPressed() {
        new AlertDialog.Builder(this)
               .setMessage("Are you sure you want to exit?")
               .setCancelable(false)
               .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
                   public void onClick(DialogInterface dialog, int id) {
                        HomeScreen.this.finish();
                   }
               })
               .setNegativeButton("No", null)
               .show();
    }

Now ,I really did not know where to call this method.Could someone give any Idea? 现在,我真的不知道在哪里调用此方法。有人可以提出任何想法吗?

when user press the back button I want to show the alert Dialog. 当用户按下后退按钮时,我要显示警报对话框。

Try below code: 试试下面的代码:

public boolean onKeyDown(int keyCode, KeyEvent event) {
    if (keyCode == KeyEvent.KEYCODE_BACK) {
        dialogOnBackPress();

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

protected void dialogOnBackPress() {

    new AlertDialog.Builder(this)
           .setMessage("Are you sure you want to exit?")
           .setCancelable(false)
           .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
               public void onClick(DialogInterface dialog, int id) {
                    HomeScreen.this.finish();
               }
           })
           .setNegativeButton("No", null)
           .show();

}

Use this: 用这个:

@Override
public boolean onKeyDown(int keyCode, KeyEvent event) {

    if (keyCode == KeyEvent.KEYCODE_BACK) {

        AlertDialog.Builder builder = new AlertDialog.Builder(this);
        builder.setTitle("Alert Message:");
        builder.setMessage("Do you want to save this image to your file??");
        builder.setPositiveButton("Yes",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub

                                           // do your stuff

                        }
                });

        builder.setNegativeButton("No",
                new DialogInterface.OnClickListener() {

                    @Override
                    public void onClick(DialogInterface dialog, int which) {
                        // TODO Auto-generated method stub
                        dialog.dismiss();
                        finish();
                    }
                });

        AlertDialog alert = builder.create();
        alert.show();

        return true;
        }

      return super.onKeyDown(keyCode, event);
    }

you can this code modify acc. 您可以将此代码修改acc。 to req. 要求

 dialog.setOnKeyListener(new Dialog.OnKeyListener() {

                @Override
                public boolean onKey(DialogInterface arg0, int keyCode,
                        KeyEvent event) {
                    // TODO Auto-generated method stub
                    if (keyCode == KeyEvent.KEYCODE_BACK) {
                        finish();
                        dialog.dismiss();
                    }
                    return true;
                }
            });

do not call super.onBackPressed(); 不要调用super.onBackPressed(); in onBackPressed onBackPressed

Else you can simply add onBackPressed() in activity_main.xml(tab.xml) as 否则,您可以简单地在activity_main.xml(tab.xml)中添加onBackPressed()作为

android:onClick="onBackPressed" mention it in your button properties android:onClick =“ onBackPressed”在按钮属性中提及

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM