Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Android View.OnKeyListener: click once, execute twice [duplicate]

Possible Duplicate:
public boolean onKey() called twice?

Here is my code

public class TestKeyActivity extends Activity {

private int i=1;
private ScrollView sv;
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);


    sv=(ScrollView) this.findViewById(R.id.read_scrollView);

    sv.setOnKeyListener(new View.OnKeyListener() {

        @Override
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (keyCode == KeyEvent.KEYCODE_DPAD_RIGHT) {

        Toast.makeText(TestKeyActivity.this, "what is wrong!!!!"+(i++), 2).show();
            return true;
            }
            return false;
        }
    });
    }
}

I use he Android emulator and Eclipse,I don't know why, but when I click the key once, the code of toast will execute twice. Is there something wrong with my code?

like image 558
lok4u Avatar asked May 01 '12 02:05

lok4u


1 Answers

I just answered a very similar question (here). The problem is that you're activating on KeyEvent.ACTION_DOWN and KeyEvent.ACTION_UP. You should only execute your code if KeyEvent.getAction() == KeyEvent.ACTION_UP

like image 164
dmon Avatar answered Oct 13 '22 16:10

dmon