Ok in my app I have a field for the user to input a number. I have the field set to only accept numbers. When the user clicks on the field it brings up the keyboard. On the keyboard (on ICS) there is a done button. I would like for the done button on the keyboard to trigger the submit button i have in my application. My code is as follows.
package com.michaelpeerman.probability;
import android.app.Activity;
import android.app.ProgressDialog;
import android.content.DialogInterface;
import android.content.DialogInterface.OnCancelListener;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.EditText;
import android.widget.TextView;
import java.util.Random;
public class ProbabilityActivity extends Activity implements OnClickListener {
private Button submit;
ProgressDialog dialog;
int increment;
Thread background;
int heads = 0;
int tails = 0;
public void onCreate(Bundle paramBundle) {
super.onCreate(paramBundle);
setContentView(R.layout.main);
submit = ((Button) findViewById(R.id.submit));
submit.setOnClickListener(this);
}
public void onClick(View view) {
increment = 1;
dialog = new ProgressDialog(this);
dialog.setCancelable(true);
dialog.setMessage("Flipping Coin...");
dialog.setProgressStyle(ProgressDialog.STYLE_HORIZONTAL);
dialog.setProgress(0);
EditText max = (EditText) findViewById(R.id.number);
int maximum = Integer.parseInt(max.getText().toString());
dialog.setMax(maximum);
dialog.show();
dialog.setOnCancelListener(new OnCancelListener(){
public void onCancel(DialogInterface dialog) {
background.interrupt();
TextView result = (TextView) findViewById(R.id.result);
result.setText("heads : " + heads + "\ntails : " + tails);
}});
background = new Thread(new Runnable() {
public void run() {
heads=0;
tails=0;
for (int j = 0; !Thread.interrupted() && j < dialog.getMax(); j++) {
int i = 1 + new Random().nextInt(2);
if (i == 1)
heads++;
if (i == 2)
tails++;
progressHandler.sendMessage(progressHandler.obtainMessage());
}
}
});
background.start();
}
Handler progressHandler = new Handler() {
public void handleMessage(Message msg) {
dialog.incrementProgressBy(increment);
if (dialog.getProgress() == dialog.getMax()) {
dialog.dismiss();
TextView result = (TextView) findViewById(R.id.result);
result.setText("heads : " + heads + "\ntails : " + tails);
}
}
};
}
You can use this one also (sets a special listener to be called when an action is performed on the EditText), it works both for DONE and RETURN:
max.setOnEditorActionListener(new OnEditorActionListener() {
@Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((event != null && (event.getKeyCode() == KeyEvent.KEYCODE_ENTER)) || (actionId == EditorInfo.IME_ACTION_DONE)) {
Log.i(TAG,"Enter pressed");
}
return false;
}
});