【问题标题】:Android: creating alert dialog when back button is pressedAndroid:按下后退按钮时创建警报对话框
【发布时间】:2014-11-07 21:15:47
【问题描述】:

我已经添加了下面的代码,所以如果在主活动中按下后退按钮,它会显示一个带有两个按钮的警报对话框以做出最终决定......但有时当我点击 YES (完成活动的肯定按钮)再次显示相同的活动而不是完成活动,我想知道我的代码中是否有任何错误...

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();   

                }

            }

【问题讨论】:

  • 在正面回应中,使用super.onBackPressed() 应该就足够了。而不是 `finish()'。
  • @TronicZomB 实际上 super.onBackPressed 调用刚刚完成()
  • @blackbelt 很高兴知道。谢谢。这就是super.onBackPressed() 所做的一切吗?
  • 你有多少次开始活动但没有完成?
  • 还有,你有碎片吗?您是否将它们添加到后台?您遇到此问题的 android 版本是什么?

标签: android android-alertdialog back-button


【解决方案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;

    }

【讨论】:

  • 当我按下积极按钮时,再次显示相同的活动,就像我们按下消极按钮一样......但有时它正在工作
  • finish();应该完成你的活动。没关系,你能不能多按一次后退按钮,告诉我会发生什么,这将有助于我帮助你
  • 发帖请看
  • 你的活动是启动器活动吗
【解决方案2】:

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

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

【讨论】:

    【解决方案3】:

    您可以在 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);
        }
    }
    

    【讨论】:

      【解决方案4】:

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

      【讨论】:

      • 当我们不导航到另一个活动时它工作正常......但是当我们导航到其他活动并按下 MainActivity.java 中的返回按钮时,它显示相同的活动而不是完成活动。 ..
      • 我认为这可能是上下文的问题.. 使用 Activity 上下文并尝试
      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2013-08-08
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-04-12
      相关资源
      最近更新 更多