Domanda

First, sorry for my low programming skills. I'm trying to write my first Java application for Android (actually I never studied Java but I get along with that most of all).

Anyway, I'm trying to make this app closing on Back button press. This is the code, with errors [1][2][3].

    @Override
[1]    public boolean onKeyDown(int keyCode, KeyEvent event)
       {
[2]        if ((keyCode == KeyEvent.KEYCODE_BACK))
       {
[3]            finish();
       }
           return super.onKeyDown(keyCode, event);
       }


/**
     * [1]KeyEvent cannot be resolved to a type
     * [2]KeyEvent cannot be resolved to a variable
     * [3]Cannot make a static reference to the non-static method finish() from the type 
          Activity
 */

Thank you all :)

È stato utile?

Soluzione

You need to import KeyEvent package which is android.view.KeyEvent... import android.view.KeyEvent;

Everytime you use a class which comes from a different package of java (java.lang is the default) you should add import to say to the compiler where it should take the class. Eclipse/IntelliJ IDEA/Netbeans help you to import packages by using a simple key combination so use one of them if you can.

For error 3: Your return is out of the method body!

What is a package?

If you want to learn more about android dev, read this.

Altri suggerimenti

If you are using an activity, try overriding the method obBackPressed

public void onBackPressed ()

Added in API level 5 Called when the activity has detected the user's press of the back key. The default implementation simply finishes the current activity, but you can override this to do whatever you want.

@Override 
public void onBackPressed(){
   // Do some stuff
   finish();
   super.onBackPressed();
}

That would save you some trouble.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top