Android:按下后退按钮时创建警告对话框

时间:2014-08-01 13:48:33

标签: android alertdialog back-button

我已添加以下代码,因此如果在主活动中按下后退按钮,则会显示一个警告对话框,其中包含两个按钮以作出最终决定...但有时当我点击时(一个积极的按钮来完成活动)再次显示相同的活动,而不是完成活动,我想知道我的代码中是否有任何错误......

MainActivity.java

public void onBackPressed() {

        //super.onBackPressed();
        Log.d("back button", "back button pressed");
        AlertDialog.Builder ad1=new AlertDialog.Builder(this);
        ad1.setMessage("Are you sure you want to exit? ");
        ad1.setCancelable(false);


        ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {             
            @Override
            public void onClick(DialogInterface arg0, int arg1) {   


            }
        });

        ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {                
            @Override
            public void onClick(DialogInterface arg0, int arg1) {   
                finish();
            }
        });
        AlertDialog alert=ad1.create();
        alert.show();   

            }

MainActivity.java完整代码

package com.vibrator;

import android.annotation.SuppressLint;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.drawable.ColorDrawable;
import android.os.Bundle;
import android.os.Vibrator;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.Button;
import android.widget.CompoundButton;
import android.widget.CompoundButton.OnCheckedChangeListener;
import android.widget.SeekBar;
import android.widget.SeekBar.OnSeekBarChangeListener;
import android.widget.Spinner;
import android.widget.TextView;
import android.widget.ToggleButton;

@SuppressLint("ShowToast")
public class MainActivity extends ActionBarActivity implements OnCheckedChangeListener, OnSeekBarChangeListener{

    ToggleButton tbutton;
    Vibrator v;
    int i=400,j=50;
    int k,l;
    TextView txt;
    SeekBar sb;
    TextView txt1;
    SeekBar sb1;
    Spinner spinner1;
    Button btn;

    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        ActionBar bar = getSupportActionBar();
        bar.setBackgroundDrawable(new ColorDrawable(Color.parseColor("#336699")));

        //Log.e("values","i value at oncreate "+i);
        //Log.e("values","i value at oncreate  "+j);
        //creating instance for vibrator
         v=(Vibrator) getSystemService(VIBRATOR_SERVICE);        
         //checking if the device has vibrator or not        
        if(v!=null){

            setContentView(R.layout.activity_main);

        }
        else {
            setContentView(R.layout.secound);
        }
            //Log.e("vibrate", "setcontentview");


        //creating instance of toggle buttton and setting listener
        tbutton=(ToggleButton) findViewById(R.id.tb1);
        tbutton.setOnCheckedChangeListener(this);


        //creating instance and setting onclicklistener for the button
        /*btn=(Button) findViewById(R.id.button);
        btn.setOnClickListener(this);*/

        sb=(SeekBar) findViewById(R.id.seekbar);
        txt=(TextView) findViewById(R.id.txt12);
        sb1=(SeekBar) findViewById(R.id.seekbar1);
        txt1=(TextView) findViewById(R.id.txt11);


        sb1.setOnSeekBarChangeListener(this);       
        sb.setOnSeekBarChangeListener(this);




    }

    @Override
    public void onCheckedChanged(CompoundButton arg0, boolean arg1) {
        //Log.d("real status", ""+arg1);
        //if vibrator is ON
        if(arg1)
        {
            Log.e("vibrate", "true vibrate");

            // Start without a delay
            // Vibrate for 100 j milliseconds
            // Sleep for 1000  (i) milliseconds 
            Log.e("values","i value "+i);
            Log.e("values","i value "+j);
            long pattern[] = {0, j, i};
            // The '0' here means to repeat indefinitely
            // '-1' would play the vibration once                       
            v.vibrate(pattern, 0);          
        }

        else {

            Log.e("vibrate", "false no v");
            //Toast.makeText(this,"status: "+arg1, Toast.LENGTH_SHORT).show();
            v.cancel();         
        }       
    }


    public void onProgressChanged(SeekBar s, int v, boolean b) {

        //switch statement to update values of seekbars
                switch (s.getId()) {
                case R.id.seekbar:
                    k=v;
                    txt.setText("Vibrator OFF time: "+k);
                    //Log.e("values","seekbar value "+k);
                    break;

                case R.id.seekbar1:
                    l=v;
                    txt1.setText("Vibrator ON time: "+l);
                    //Log.e("values","seekbar1 value "+l);
                    break;

                }   
        //seekbarchanged method implementation
        if (tbutton.isChecked()) {
            Log.e("values","yes tbutton is checked");   
        tbutton.setChecked(false);
        switch (s.getId()) {
        case R.id.seekbar:
            i=k;            
            //Log.e("true", "seekbar tbutton checked "+i);
            break;

        case R.id.seekbar1:
            j=l;
            //Log.e("true", "seekbar1 tbutton checked "+j);
            break;      
        }       
        Log.e("true", "set true");
        tbutton.setChecked(true);

    }       
        else{
            //Toast.makeText(this,"Set ON to customize", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder ad=new AlertDialog.Builder(this);
            ad.setTitle("Instruction");
            ad.setMessage("Set the button ON to customize");
            ad.setNeutralButton("OK", new DialogInterface.OnClickListener() {               
                @Override
                public void onClick(DialogInterface arg0, int arg1) {                   
                }
            });
            ad.show();
        }


    }

    @Override
    public void onStartTrackingTouch(SeekBar arg0) {        
    }
    @Override
    public void onStopTrackingTouch(SeekBar arg0) {     
    }


    @Override


public boolean onCreateOptionsMenu(Menu menu) {

        MenuInflater inflate= getMenuInflater();
        inflate.inflate(R.menu.menu_v, menu);
        return super.onCreateOptionsMenu(menu);
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        switch (item.getItemId()) {
        case R.id.menu_setting:     
            break;

        case R.id.about:
            //Toast.makeText(this, "about clicked", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder ad=new AlertDialog.Builder(this);
            ad.setTitle("About");
            ad.setMessage("This app is developed by Rajesh Uragonda");
            ad.setNeutralButton("OK", new DialogInterface.OnClickListener() {               
                @Override
                public void onClick(DialogInterface arg0, int arg1) {                   
                }
            });
            ad.show();          
            break;  

        case R.id.settings:
            //Toast.makeText(this, "settings clicked", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder ad2=new AlertDialog.Builder(this);
            ad2.setTitle("Settings");
            ad2.setMessage("Your settings here");
            ad2.setNeutralButton("OK", new DialogInterface.OnClickListener() {              
                @Override
                public void onClick(DialogInterface arg0, int arg1) {                   
                }
            });
            ad2.show(); 
            break;
        case R.id.help:
            //Toast.makeText(this, "help clicked", Toast.LENGTH_SHORT).show();
            AlertDialog.Builder ad1=new AlertDialog.Builder(this);
            ad1.setTitle("Help");
            ad1.setMessage(R.string.alerthelp);
            ad1.setNeutralButton("OK", new DialogInterface.OnClickListener() {              
                @Override
                public void onClick(DialogInterface arg0, int arg1) {                   
                }
            });
            ad1.show();


            break;



        }
        return super.onOptionsItemSelected(item);


}

    @Override
    protected void onPause() {
        // TODO Auto-generated method stub

        super.onPause();
        if (tbutton.isChecked()) {
            tbutton.setChecked(false);
            Log.d("onpause", "onpause mainactivity tbutton");
        }
        Log.d("onpause", "onpause mainactivity");

    }


    //responds to the button at top used as navigation to next activity
    public void btn(View v){
        //Button btn1=(Button) findViewById(R.id.btn1);
        Intent i = new Intent(MainActivity.this, CustomPatterns.class);
        startActivity(i);
        }

    //when back button pressed it goes directly to home
    public void onBackPressed() {

        //super.onBackPressed();
        Log.d("back button", "back button pressed");
        AlertDialog.Builder ad1=new AlertDialog.Builder(this);
        ad1.setMessage("Are you sure you want to exit? ");
        ad1.setCancelable(false);


        ad1.setNegativeButton("NO", new DialogInterface.OnClickListener() {             
            @Override
            public void onClick(DialogInterface arg0, int arg1) {   


            }
        });

        ad1.setPositiveButton("YES", new DialogInterface.OnClickListener() {                
            @Override
            public void onClick(DialogInterface arg0, int arg1) {   

                MainActivity.this.finish();
            }
        });
        AlertDialog alert=ad1.create();
        alert.show();   

                }

            }

4 个答案:

答案 0 :(得分:1)

在您的活动中使用此代码

public void onBackPressed() {
  AlertDialog diaBox = AskOption();
  diaBox.show();
}

private AlertDialog AskOption()
 {
    AlertDialog myQuittingDialogBox =new AlertDialog.Builder(this) 
        .setTitle("Exit") 
        .setMessage("Are you sure you want to exit?") 

        .setPositiveButton("Yes", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int whichButton) { 
            finish();
            }   
        })
        .setNegativeButton("No", new DialogInterface.OnClickListener() {
            public void onClick(DialogInterface dialog, int which) {
                dialog.dismiss();
            }
        })
        .create();
        return myQuittingDialogBox;

    }

答案 1 :(得分:0)

另一种方法是将活动上下文传递给构造函数中的对话框,并使用context.finish()完成它。

dismiss();//dismiss dialog first
context.finish();//then finish the hosting activity

答案 2 :(得分:0)

你可以在MenuItem上使用alertdialog onclick ...

只需查看下面的代码.. 谢谢

public boolean onOptionsItemSelected(MenuItem item)
{           
    switch (item.getItemId())
    {
    case R.id.menu_cgoal:
        Toast.LENGTH_SHORT).show();

        final EditText input = new EditText(Myclass.this);
        LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.MATCH_PARENT);
        input.setLayoutParams(lp);
        //input.setImeOptions(EditorInfo.IME_ACTION_DONE);
        AlertDialog.Builder ad=new AlertDialog.Builder(Myclass.this);
        ad.setView(input);
        ad.setTitle("Create goal...");
        ad.setMessage("Are you sure you want to add this goal?");

        ad.setNeutralButton("OK", new DialogInterface.OnClickListener() {               
            @Override
            public void onClick(DialogInterface arg0, int arg1) { 
                String value = input.getText().toString().trim();
                Toast.makeText(getApplicationContext(), value, Toast.LENGTH_SHORT).show();
            }
        });
        ad.show();
        return true;
    default:
        return super.onOptionsItemSelected(item);
    }
}

答案 3 :(得分:-1)

不只是finish()。使用MainActivity.this.finish();