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
Related
A beginner here, I am looking to make a simple app in which there are 4 sequential EditTexts, and as soon as the first EditText is completed and the user presses 'enter', the focus is automatically taken to the next EditText and the first EditText disappears.
I have used an 'onKey listener'. However, whenever the enter key is pressed for the first EditText, both the first and second EditText fields disappear.
Here is the code
public class MainActivity extends AppCompatActivity {
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final EditText ko = findViewById(R.id.one);
final EditText ma = findViewById(R.id.two);
final EditText ko1 = findViewById(R.id.three);
final EditText xa = findViewById(R.id.four);
final TextView te = findViewById(R.id.ko);
ko.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko.setVisibility(View.INVISIBLE);
ma.requestFocus();
}
return false;
}
});
ma.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent k) {
if(i == KeyEvent.KEYCODE_ENTER) {
ma.setVisibility(View.INVISIBLE);
ko1.requestFocus();
}
return false;
}
});
ko1.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent t) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko1.setVisibility(View.INVISIBLE);
xa.requestFocus();
}
return false;
}
});
}
public void onClick(View v){
EditText ko = findViewById(R.id.one);
EditText ma = findViewById(R.id.two);
EditText ko1 = findViewById(R.id.three);
EditText xa = findViewById(R.id.four);
String t = ko.getText().toString();
String u = ma.getText().toString();
String x = ko1.getText().toString();
String w = xa.getText().toString();
String total = t +" "+ u +" "+x + " " +w;
Toast.makeText(this, total,Toast.LENGTH_LONG).show();
}
}
The event will continue to bubble up the container chain if you return false
Returns True if the listener has consumed the event, false otherwise.
ko.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko.setVisibility(View.INVISIBLE);
ma.requestFocus();
}
return true;//change this line and all its occurances
}
});
Return true after requesting focus. Refer View.OnKeyListener
True if the listener has consumed the event, false otherwise.
public boolean onKey(View view, int i, KeyEvent keyEvent) {
if(i == KeyEvent.KEYCODE_ENTER) {
ko.setVisibility(View.INVISIBLE);
ma.requestFocus();
return true; // this will consume the Enter event
}
return false;
}
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("");
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 saw many posts on this subject but couldnt find the right answer for me.
I have an activity that dims when i pop the popup window.
the back button working but only the second time i press it, the first press dismiss the popup but its not un-dim the activity because i cant catch the event from the popupwindows, the second press is catched by the activity and only then i can un-dim it.
here are my tries to accomplish this:
m_PopupWindow.setBackgroundDrawable(new BitmapDrawable());
m_PopupWindow.setOutsideTouchable(true);
View popUpWindowLaout = m_PopupWindow.getContentView();
popUpWindowLaout.setFocusableInTouchMode(true);
//first press doesnt get caught here
popUpWindowLaout.setOnKeyListener(new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
if (keyCode == KeyEvent.KEYCODE_BACK)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
return true;
}
}
});
//this func will catch the second press and will work, but i want the first press will do it.
#Override
public void onBackPressed() {
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
super.onBackPressed();
}
}
change
public void onBackPressed() {
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
super.onBackPressed();
}
}
to
public void onBackPressed() {
super.onBackPressed();
if (m_PopupWindow != null)
{
m_ActionBar.show();
unShadeTheActivity();
m_PopupWindow.dismiss();
}
else
{
// rest of the code
// you can use finish,dismiss or call startActivity
// finish();
}
}
popupWindow.setOnShowListener(HandlePopupShowLister);
popupWindow.setOnDismissListener(HandlePopUpDismissListerner);
public static OnDismissListener HandlePopUpDismissListerner = new OnDismissListener() {
#Override
public void onDismiss(DialogInterface dialog) {
// TODO Auto-generated method stub
Log.i("HandlePopUpDismissListerner", "HandlePopUpDismissListerner");
CommonVariable.IsPopupOpen = false;
}
};
public static OnShowListener HandlePopupShowLister = new OnShowListener() {
// onShowListener interface.
#Override
public void onShow(DialogInterface dialog) {
Log.i("HandlePopupShowLister", "HandlePopupShowLister");
// TODO Auto-generated method stub
CommonVariable.IsPopupOpen = true;
}
};
I'm having some trouble with a simple dialog i'm working on. I have three different TextView's that when they are clicked I have a dialog box pop up with only the Title and one EditText. I'm trying to make it so I use the same custom dialog for all three text views, but depending on which TextView is tapped the dialog set the new value to that TextView. Below is my code:
#Override
protected Dialog onCreateDialog(int id) {
super.onCreateDialog(id);
CustomDialogPercent dialog = null;
switch(id){
case 1:
dialog = new CustomDialogPercent(this, id);
dialog.setTitle("Shipping Percent");
dialog.show();
break;
case 2:
dialog = new CustomDialogPercent(this, id);
dialog.setTitle("Tax Percent");
dialog.show();
break;
case 3:
dialog = new CustomDialogPercent(this, id);
dialog.setTitle("Commission Percent");
dialog.show();
break;
default:
dialog = null;
}
return dialog;
}
private void registerListeners() {
shippingPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(1);
}
});
taxPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(2);
}
});
commissionPercent.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
showDialog(3);
}
});
}
public class CustomDialogPercent extends Dialog {
int id = 0;
public CustomDialogPercent(Context context, int id) {
super(context);
this.id = id;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.basic_dialog);
basicDialogEntry = (EditText) findViewById(R.id.basic_dialog_entry);
basicDialogEntry.setKeyListener(DigitsKeyListener.getInstance(true,true));
}
#Override
public void onStart() {
super.onStart();
switch(id) {
case 1:
basicDialogEntry.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(basicDialogEntry.getWindowToken(), 0);
shippingPercent.setText(basicDialogEntry.getText().toString());
try {
if ((Float.parseFloat(basicDialogEntry.getText().toString())) < 0) {}
}catch(Exception ex) {
shippingPercent.setText("0");
}
mathCalculations();
CustomDialogPercent.this.dismiss();
}
return false;
}
});
break;
case 2:
basicDialogEntry.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(basicDialogEntry.getWindowToken(), 0);
taxPercent.setText(basicDialogEntry.getText().toString());
try {
if ((Float.parseFloat(basicDialogEntry.getText().toString())) < 0) {}
}catch(Exception ex) {
taxPercent.setText("0");
}
mathCalculations();
CustomDialogPercent.this.dismiss();
}
return false;
}
});
break;
case 3:
basicDialogEntry.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View v, int keyCode, KeyEvent event) {
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(basicDialogEntry.getWindowToken(), 0);
commissionPercent.setText(basicDialogEntry.getText().toString());
try {
if ((Float.parseFloat(basicDialogEntry.getText().toString())) < 0) {}
}catch(Exception ex) {
commissionPercent.setText("0");
}
mathCalculations();
CustomDialogPercent.this.dismiss();
}
return false;
}
});
break;
}
}
}
OK. With this code what is happening is the first time I tap each TextView they work perfectly. But once I tap any of them again the dialog boxes pop up correctly with the correct title, but values that are set back to the TextView are incorrect.
Example; i enter 8 for the shippingPercent and them 25 for the commissionPercent. And then i go back to shippingPercent and enter 5. The 5 doesn't get set. Instead it will be 25. If i keep using the dialog boxes it seems like my mathCalculations() stops working aswell.
Thanks for all the help.
Maybe you could assign a variable
activeTextView = theTextViewYouWant;
...then update activeTextView with the value you want?