简体   繁体   English

View.OnKeyListener曾为我的活动工作过一次,不再工作了

[英]View.OnKeyListener worked once for my activity, does not work anymore

I have an Activity that implemented View.OnKeyListener so that it could catch when the user hit the back button and would pop up a dialog. 我有一个Activity实现了View.OnKeyListener以便当用户点击后退按钮并弹出对话框时它可以捕获。 Previously, it worked just fine. 以前,它工作得很好。 Recently, however, it has stopped working and the app would just pretend that there was no onKey method to catch the Back button. 然而,最近,它已停止工作,应用程序只是假装没有onKey方法来捕获后退按钮。 I can't seem to figure out why, as I've barely touched the onKey method since I made the changes. 我似乎无法弄清楚为什么,因为我做了更改后几乎没有触及onKey方法。 I tried just using OnBackPressed() instead, but that didn't solve anything and in fact created weird and unpredictable behavior. 我尝试使用OnBackPressed()代替,但这并没有解决任何问题,实际上创造了奇怪和不可预测的行为。 Can anyone help me figure out why it seems like my app is letting the system take the reigns on the back button? 任何人都可以帮我弄清楚为什么我的应用程序似乎让系统采取后退按钮的统治?

Here's the important parts of my implementation: 这是我实施的重要部分:

import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockFragmentActivity;
import com.actionbarsherlock.view.Menu;
import com.actionbarsherlock.view.MenuItem;
import com.actionbarsherlock.view.MenuInflater;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.preference.PreferenceManager;
import android.view.KeyEvent;
import android.view.View;

public class NagTasksAddTasksActivity extends SherlockFragmentActivity implements View.OnKeyListener {
    //various parameters
    public void onCreate(Bundle savedInstanceBundle)
    {
        super.onCreate(savedInstanceBundle);
        SharedPreferences prefs = PreferenceManager.getDefaultSharedPreferences(getBaseContext());
        String setTheme = prefs.getString("themeselect", "Dark Overflow");
        if (setTheme.toLowerCase().contentEquals("dark overflow")){
            setTheme(R.style.Theme_Sherlock_ForceOverflow);
        } else if (setTheme.toLowerCase().contentEquals("light overflow")){
            setTheme(R.style.Theme_Sherlock_Light_ForceOverflow);
            isDarkThemeUsed = false;
        } else if (setTheme.toLowerCase().contentEquals("dark menu")){
            setTheme(R.style.Theme_Sherlock);
        } else if (setTheme.toLowerCase().contentEquals("light menu")){
            setTheme(R.style.Theme_Sherlock_Light);
            isDarkThemeUsed = false;
        }
        setContentView(R.layout.createtasklayout);
        ActionBar actionBar = getSupportActionBar();
        setTitle(R.string.newTask);

    }
    ...
    @Override
    public boolean onKey(View v, int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK)
        {
            AlertDialog.Builder builder = new AlertDialog.Builder(this);
            builder.setCancelable(true);
            builder.setTitle(R.string.wait);
            builder.setMessage(R.string.confirmbackkey);
            builder.setPositiveButton(R.string.save, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    //stuff
                    dialog.dismiss();
                }
            });
            builder.setNegativeButton(R.string.discard, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    AlertDialog.Builder subBuilder = new AlertDialog.Builder(getParent());
                    subBuilder.setCancelable(true);
                    subBuilder.setTitle(R.string.wait);
                    subBuilder.setMessage(R.string.confirmdiscard);
                    subBuilder.setPositiveButton(R.string.yes, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            //more stuff
                            dialog.dismiss();
                        }
                    });
                    subBuilder.setNegativeButton(R.string.no, new DialogInterface.OnClickListener() {

                        @Override
                        public void onClick(DialogInterface dialog, int which) {
                            dialog.cancel();
                        }
                    });
                    dialog.dismiss();
                    subBuilder.create().show();
                }
            });
            builder.setNeutralButton(R.string.cancel, new DialogInterface.OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    dialog.cancel();
                }
            });
            builder.create().show();
            return true;
        }
        return false;
    }
}

Another way to catch the back button is to use the dispatchKeyEvent method in the Activity (you don't need to implement View.OnKeyListener). 捕获后退按钮的另一种方法是在Activity中使用dispatchKeyEvent方法(您不需要实现View.OnKeyListener)。 This seems to work for me every time. 这似乎每次对我都有用。

public class HomeActivity extends Activity
{
...

    @Override
    public boolean dispatchKeyEvent(KeyEvent event) 
    {
        int action = event.getAction();
        int keyCode = event.getKeyCode();
        switch (keyCode) 
        {
            case KeyEvent.KEYCODE_BACK:
                if (action == KeyEvent.ACTION_DOWN)
                {
                    Log.v("myApp", "Back button pressed.");
                    return true;
                }
            default:
                return false;
        }
        return false;
    }
}

Try removing the return true under builder.create().show(); 尝试删除builder.create().show();下的return true builder.create().show(); and change the return false into return true and see if it works. 并将return false更改为return true并查看它是否有效。 this should let them all to return results when a KeyEvent is initialized. 这应该让他们在初始化KeyEvent时返回结果。

The simplest way to do this is to override OnBackPressed and fill in the code you want to have happen when someone presses the back button. 最简单的方法是覆盖OnBackPressed并填写您想要在有人按下后退按钮时发生的代码。

just make sure you delete the super.OnBackPressed line. 只需确保删除super.OnBackPressed行。

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

相关问题 View.OnKeyListener不起作用 - View.OnKeyListener does not work 将View.OnKeyListener附加到SurfaceView - Attaching a View.OnKeyListener to a SurfaceView 用于软键盘的View.OnKeyListener - View.OnKeyListener for soft keyboard 覆盖View.OnKeyListener中的onKey的问题 - Issues overriding onKey in View.OnKeyListener IME_ACTION_DONE似乎在Android上破坏了View.OnKeyListener - IME_ACTION_DONE seems to destroy the View.OnKeyListener on Android Android(里程碑/ Droid):View.OnKeyListener无法正常工作? - Android (Milestone/Droid): View.OnKeyListener not working correctly? edittext.setOnKeyListener(new View.OnKeyListener) 的问题 - Problem with edittext.setOnKeyListener(new View.OnKeyListener) 如何解决类型View中的“setOnKeyListener(View.OnKeyListener)不适用于android上的参数(new OnKeyListener(){})”错误? - How to solve “setOnKeyListener(View.OnKeyListener) in the type View is not applicable for the arguments (new OnKeyListener(){})” error on android? 为什么构造函数ArrayAdapter <String> (新的View.OnKeyListener(){},int,String [])未定义 - Why The constructor ArrayAdapter<String>(new View.OnKeyListener(){}, int, String[]) is undefined Android意图街景视图不再有效 - Android intent Street View does not work anymore
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM