I am making this try-out game and after someone guesses a number, the EditText view, needs to be cleared.
Here is my onCreate:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_game);
Button b = (Button) findViewById(R.id.check);
final EditText input = (EditText) findViewById(R.id.number);
b.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (!input.getText().toString().matches("")) {
input.setText("");
handleGuess(Integer.parseInt(input.getText().toString()));
} else {
Toast.makeText(getApplicationContext(), "Je hebt geen nummer ingevuld!", Toast.LENGTH_SHORT)
.show();
}
}
});
input.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)) {
if (!input.getText().toString().matches("")) {
input.setText("");
handleGuess(Integer.parseInt(input.getText().toString()));
} else {
Toast.makeText(getApplicationContext(), "Je hebt geen nummer ingevuld!", Toast.LENGTH_SHORT)
.show();
}
}
return false;
}
});
}
Whenever I try to press Enter on my softkeyboard or press the button, it just says "RaadHetGetal stopped."
Any ideas? If you need to see any more, just say it.
In your both listeners you have at least this error:
You set the text to nothing
input.setText("");
And try to parse an int from it directly after. This results in NumberFormatException
handleGuess(Integer.parseInt(input.getText().toString()));
So if you want to clear the text after handleGuess, you can call clear().
handleGuess(Integer.parseInt(input.getText().toString()));
input.clear();
Right, you obtain a java.lang.NumberFormatException, at line:
Integer.parseInt(input.getText().toString())
Since you are setting your TextView as empty with the code line:
input.setText("");
Related
I am making an app that sends data over bluetooth to a HC-06. When I type something in the EditText and press send, the EditText loses focus. I found out this happens because I call a backgound thread with write().
How can I keep focus?
messageEdTxt = findViewById(R.id.message_edtxt);
messageEdTxt.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEND) {
String messageEdtxt = messageEdTxt.getText().toString();
messageEdTxt.setText("");
write(messageEdtxt);
return true;
} else {
return false;
}
}
});
sendBtn = findViewById(R.id.send_btn);
sendBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
String messageEdtxt = messageEdTxt.getText().toString();
write(messageEdtxt);
messageEdTxt.setText("");
}
});
The mConnectedThread is a custom thread to send messages.
private void write(String message) {
if (mSocket.isConnected()) {
if (mConnectedThread != null) {
mConnectedThread.write(message.getBytes(StandardCharsets.UTF_8));
} else {
finish();
}
} else {
finish();
}
}
Did you try
messageEdTxt.requestFocus();
on clicking sendBtn
i am creating my custom EditText which validate email and other things on focus lost and if it is not valid then focus back. It works fine if i have only one EditText but when i have multiple EditText it infinity focuses between my editText boxes as it try to check validation in both. Here is my sample code.
public void init(){
this.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
// TODO Auto-generated method stub
final MyEditText ed = MyEditText.this;
//...............check require field validation
if(!hasFocus && isRequire){
if(ed.getText().toString().length()<=0){
String msg = "Require Field";
v.clearFocus();
setErrorMsg(ed,msg);
return;
}
}else if(ed.getText().toString().length()>0){
ed.setError(null);
}
}
}
private void setErrorMsg(final EditText ed,String msg){
if(errorMessage!=null && errorMessage.length()>0){
msg = errorMessage;
}
ed.setError(msg);
ed.post(new Runnable() {
public void run() {
ed.requestFocus();
}
});
}
Put onfocus change lisner on the parent view from the viewGroup get the child view and chek it u will get the perticular edittext. i had some requirement like that i solved it this way.
TableLayout tableView = (TableLayout)findViewById(R.id.mydetails_tableview);
View mytempView=null;
int noOfChilds=tableView.getChildCount();
for(int i=0;i<noOfChilds;i++)
{
mytempView=tableView.getChildAt(i);
if(i%2==0)
{
View vv=((TableRow) mytempView).getChildAt(1);
if(vv instanceof EditText)
{
//Log.v("This one is edit text---", "here there");
((EditText) vv).setText("");
}
}
}
boolean pendingFocus = false;
Before
ed.post(new Runnable() {
public void run() {
ed.requestFocus();
}
});
Add
pendingFocus = true;
and Replace:
if(!hasFocus && isRequire){
with
if(!hasFocus && isRequire && !pendingFocus){
Finally reset pendingFocus with a new else statement here:
if(ed.getText().toString().length()<=0){
String msg = "Require Field";
v.clearFocus();
setErrorMsg(ed,msg);
return;
}
}else if(ed.getText().toString().length()>0){
ed.setError(null);
}else{
pedingFocus = false;
}
I generate multiple EditText in a for-loop and want to update a "score" when focus is lost from one of the EditTexts. I also wish to check that the input is valid and if not, empty the EditText and set focus back to it.
The following code adds EditTexts and a onFocusChangeListener.
The problem is that when a score is not valid (updateScore(id) returns false), I want to empty the EditText and set the focus back to this view.
The problem in my code is that if I enter a value in EditText A that are not valid, and then click in EditText B. Both A and B have focus... I only want A to have focus...
How can I set the focus back to the previous EditText and be ready for new inputs to this view?
for (int player = 0; player < numPlayers; player++)
{
EditText valueET = new EditText(this);
valueET.setOnClickListener(new OnClickListener() {
#Override public void onClick(View v) {
Log.v("Focus", "Lagrer unna den som har blitt klikket, " + String.valueOf(v.getId()));
etHasFocus = (EditText) v;
}
});
valueET.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
{
if(!updateScore(v.getId()))
{
if (etHasFocus != null && v.getId() != etHasFocus.getId())
etHasFocus.clearFocus();
v.requestFocus();
}
});
valueET.setId(200+player*100+row);
valueET.setInputType(InputType.TYPE_CLASS_NUMBER);
valueET.setTextColor(Color.BLACK);
valueET.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
tr.addView(valueET);
}
tl.addView(tr, new TableLayout.LayoutParams( LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
The code for updateScore(id) is (simplified):
boolean updateScore(int id)
{
EditText t = (EditText) findViewById(id);
String text = t.getText().toString();
if( !text.equals(""))
{
int score = Integer.parseInt(text);
}
if(score != 9)
return false;
TextView total = (TextView) findViewById(ID_toal);
t2.setText(String.valueOf(score));
return true;
}
Code is updated, problem now is that onClick never is called... (So etHasFocus = null)
You can try keeping a track of which EditText has been clicked. For this, create a EditText variable:
EditText etHasFocus;
In addition to adding OnFocusChangeListener, add an OnClickListener as well:
valueET.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
etHasFocus = (EditText) v;
}
});
Now, inside your OnFocusChangeListener, make the following changes:
valueET.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus) {
if(!updateScore(v.getId())) {
// Clear focus from another EditText
if (etHasFocus != null && v.getId() != etHasFocus.getId()) {
etHasFocus.clearFocus();
}
v.requestFocus();
}
}
}
});
Edit:
You are right. the onClick(View) method is called on second click. I can suggest you an alternate approach. I have tried it and its working fine:
Create a EditText variable:
EditText etCurrent;
Set an OnTouchlistener on each EditText:
valueET.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
if (etCurrent != null) {
if (etCurrent.getId() != v.getId()) {
if (!check(etCurrent.getId())) {
etCurrent.setSelection(0,
etCurrent.getText().toString().length());
return true;
} else {
etCurrent = (EditText) v;
}
}
} else {
etCurrent = (EditText) v;
}
}
return false;
}
});
Remove OnClickListener, onFocusChangeListener and etHasFocus.
You don't need to initialize etCurrent as if (etCurrent != null) { } else { } takes care of that.
In my android app I have the following code in the OnCreate function:
txtUsername.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
// TODO Auto-generated method stub
String Username = txtUsername.getText().toString();
if (arg1 == KeyEvent.KEYCODE_ENTER) {
DontShowDialog = false;
if ((Username.toLowerCase().endsWith("blabla.com") == false && Username.toLowerCase().endsWith("blabla-bla.nl") == false) || validateEmail(Username) == false) {
final Dialog dialog = new Dialog(arg0.getContext());
dialog.setContentView(R.layout.startdialog);
dialog.setTitle("Warning 1");
Button btOk = (Button) dialog.findViewById(R.id.btOk);
btOk.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
DontShowDialog = true;
dialog.dismiss();
return;
}
});
if (DontShowDialog == false) {
dialog.show();
}
return false;
}
}
txtUsername.clearFocus();
txtPassword.setNextFocusDownId(txtPassword.getId());
return false;
}
});
When the user hits the NEXT button and the username is not right, a dialog is shown which can be canceled by the OK button.
But.... after hitting the OK button, the dialog is shown again... I don't want that.
Why is that happening?
rg,
Eric
By returning false in your onKey() event, you're telling Android that the KeyEvent was not consumed - so my guess is that changing the return statement to true might fix the problem, because Android would know the event was consumed, and it would not re-enter the onKey() method. If you could try that out and share the results that would be great!
Solved it.
moved the line
DontShowDialog = true;
from the OnClick part
Changed the if-then below the onClick to:
if (DontShowDialog == false) {
dialog.show();
DontShowDialog = true;
return false;
}
I am a Java rookie and need some help with my code.
I am trying to get a variable out of the code below so that I later on can make the numbers that you write in the EditText field display in as a TextView.
The code:
public class MoneyTickerActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final EditText edittext = (EditText) findViewById(R.id.editText1);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
Toast.makeText(MoneyTickerActivity.this, edittext.getText(), Toast.LENGTH_SHORT).show();
return true;
}
return false;
}
});
}
}
// get text view
final TextView texView = (TextView) findViewById(R.id.textView1);
and instead of
Toast.makeText(MoneyTickerActivity.this, edittext.getText(), Toast.LENGTH_SHORT).show();
make
textView.setText(edittext.getText());