问题描述:

My //key listener doesn't seem to do the job.

After pressing enter the soft keyboard closes, and that's all

I followed this stackoverflow question

public void takeTheGuess(View view) {

//loading stats

stats();

EditText editText = (EditText) findViewById(R.id.editText);

//key listener

editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {

public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {

if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {

//enter is pressed, do stuff

//trying to show a simple message for testing now

int duration = Toast.LENGTH_SHORT;

Context context = getApplicationContext();

Toast toast = Toast.makeText(context, "hello there, you just pressed enter", duration);

toast.show();

}

return false;

}

});

//fixing the blank field

try {

userNumber = Integer.parseInt(editText.getText().toString());

} catch (Exception e) {

int duration = Toast.LENGTH_SHORT;

Context context = getApplicationContext();

String message = "Don't leave this field blank!";

Toast err = Toast.makeText(context, message, duration);

//positioning our toast

err.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);

err.show();

}

String message = null;

if (myNumber == 0) {

losowanie();

}

if (userNumber > myNumber && editText.getText().length() > 0) {

message = "My number is smaller than yours.";

} else if (userNumber < myNumber && editText.getText().length() > 0) {

message = "My number is bigger than yours.";

} else if (userNumber == myNumber && editText.getText().length() > 0) {

message = "Bullseye !";

timesGuessed++;

losowanie();

if (timesGuessed > score) {

SharedPreferences sharedPreferences = getSharedPreferences("com.example.dawid.zgadnijliczbe", Context.MODE_PRIVATE);

SharedPreferences.Editor editor = sharedPreferences.edit();

editor.putInt("score_pref", timesGuessed);

editor.commit();

}

stats();

}

if (editText.getText().length() > 0) {

//showing up our toast

int duration = Toast.LENGTH_SHORT;

Context context = getApplicationContext();

Toast toast = Toast.makeText(context, message, duration);

//positioning our toast

toast.setGravity(Gravity.CENTER_VERTICAL | Gravity.CENTER_HORIZONTAL, 0, 0);

toast.show();

TextView text_times = (TextView) findViewById(R.id.text_times);

text_times.setText("Times guessed: " + timesGuessed);

}

}

相关阅读:
Top