I have Two EditTexts. I want On First EditTexts click clear the second and on second edittext click clear the first one. So I have tried OnClickListener and OnTouchListener. But it is not working properly.
et_email.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!(et_email.getText().toString().equalsIgnoreCase("") && et_mobile.getText().toString().equalsIgnoreCase(""))) {
if (MotionEvent.ACTION_UP == event.getAction()) {
et_mobile.setText("");
et_mobile.setFocusableInTouchMode(true);
et_mobile.setFocusable(true);
et_mobile.requestFocus();
}
return true; // return is important...
} else
return false;
}
});
et_mobile.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if (!(et_email.getText().toString().equalsIgnoreCase("") && et_mobile.getText().toString().equalsIgnoreCase(""))) {
if (MotionEvent.ACTION_UP == event.getAction()) {
et_email.setText("");
et_mobile.setFocusableInTouchMode(true);
et_mobile.setFocusable(true);
et_mobile.requestFocus();
}
return true; // return is important...
}
else
return false;
}
});
But the problem is Focus is not setting on first touch and while clicking and unable to clear EditText.
First add this to your Edittext layouts:
android:focusableInTouchMode="false"
Without this line, the EditText will react to touch-mode, and only listen to your onClick() the second time you click your EditText bar.
This will disable touch-mode for EditText, and fire onClick() in first time
focusableInTouchMode
Note: boolean that controls whether a view can take focus while in touch mode. If this is true for a view, that view can gain focus when clicked on, and can keep focus if another view is clicked on that doesn't have this attribute set to true.
than do as follows:
EditText1
EditText et_email = (EditText) findViewById(R.id.yourEditText1);
et_email.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do this
et_mobile.setText("");
//or this
et_mobile.getText().clear();
}
});
EditText2
EditText et_mobile = (EditText) findViewById(R.id.yourEditText2);
et_mobile.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//do this
et_email.setText("");
//or this
et_email.getText().clear();
}
});
This should help u out.
you are clearing the first one one touching the first one, change your variable names in first listener like this
if (!(et_email.getText().toString().equalsIgnoreCase("") && et_mobile.getText().toString().equalsIgnoreCase(""))) {
if (MotionEvent.ACTION_UP == event.getAction()) {
et_mobile.setText("");
et_email.setFocusableInTouchMode(true);
et_email.setFocusable(true);
et_email.requestFocus();
}
return true; // return is important...
} else
I hope this code helps you (it works for me)
edit1 = (EditText) findViewById(R.id.edit1);
edit2 = (EditText) findViewById(R.id.edit2);
edit1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
edit2.setText("");
}
});
edit2.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
edit1.setText("");
}
});
Related
I have a vertical scrolling layout with multiple EditText and Spinner controls.
Problem is when i choose any spinner option after selection the screen scrolls back to the last EditText is was editing before this spinner. The Focus remains with the last EditText i was editing. Is there a way i can keep focus with the current selected spinner.
I am looking for a solution that can be implemented on all spinners from layout XML or some generic method to apply to all spinners.
Here's my solution.
mSpinner.setFocusableInTouchMode(true);
mSpinner.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
if (mSpinner.getWindowToken() != null) {
mSpinner.performClick();
}
}
}
});
Use this to avoid EditText Focus :
scrollView = (ScrollView) findViewById(R.id.scrollView_id);
scrollView.setOnTouchListener(new OnTouchListener() {
// to solve foocus problem on scrolling
public boolean onTouch(View v, MotionEvent event) {
if (myEditText.hasFocus()) {
myEditText.clearFocus();
}
if (myEditText1.hasFocus()) {
myEditText1.clearFocus();
}
return false;
}
});
I solved the problem with the help of Ryderz answer. here is the code :
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
scrollView = (ScrollView) findViewById(R.id.sv_main);
scrollView.setOnTouchListener(new OnTouchListener() {
// to solve focus problem on scrolling
public boolean onTouch(View v, MotionEvent event) {
IBinder windowToken = null;
if (myEditText1.hasFocus()) {
myEditText1.clearFocus();
windowToken = myEditText1.getWindowToken();
}
if (myEditText2.hasFocus()) {
myEditText2.clearFocus();
windowToken = myEditText2.getWindowToken();
}
if (myEditText3.hasFocus()) {
myEditText3.clearFocus();
windowToken = myEditText3.getWindowToken();
}
if (windowToken != null) {
imm.hideSoftInputFromWindow(windowToken, 0);
}
scrollView.requestFocusFromTouch();
return false;
}
});
Then I set the android:focusable="true" for my textViews so that on scroll when focus is removed from editText then the Textviews can be picked for focus. In that way the user doesn't see any focused control on screen.
I had the same problem like you and I've resolved with this solution.
I've redefined OnItemSelectedListener and when the spinner changes the value, I take the focus and after that, I release again.
This is my class CustomOnItemSelectedListener:
public class CustomOnItemSelectedListener implements AdapterView.OnItemSelectedListener{
private Spinner mSpinner;
private int iCurrentSelection;
public CustomOnItemSelectedListener(Spinner s){
mSpinner = s;
iCurrentSelection = mSpinner.getSelectedItemPosition();
}
#Override
public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2,
long arg3) {
if (iCurrentSelection != arg2) {
mSpinner.setFocusableInTouchMode(true);
mSpinner.requestFocus();
mSpinner.setFocusableInTouchMode(false);
mSpinner.clearFocus();
}
iCurrentSelection = arg2;
}
#Override
public void onNothingSelected(AdapterView<?> arg0) {
//No hace falta hacer nada
}
}
In my code I do this
Spinner spinner = (Spinner) rootView.findViewById(R.id.spinner);
spinner.setOnItemSelectedListener(new CustomOnItemSelectedListener(spinner));
If you want to keep focus, don't do "clearFocus()".
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.
I have a number of EditText elements in my page along with two buttons. I want the user to touch on any one EditText field and click any button to insert a certain value into that very EditText field they touched. Giving input using the keypad is not allowed. Please help me to do this.
You can use View.OnFocusChangeListener to detect if any view (edittext) gained or lost focus.
for (EditText view : editList){
view.setOnFocusChangeListener(focusListener);
}
....
private OnFocusChangeListener focusListener = new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){
focusedView = v;
} else {
focusedView = null;
}
}
}
This goes in your activity or fragment or wherever you have the EditTexts. The .... is just saying that you can put it anywhere else in the class. And obviously you would need to create an array with them in it, thus the editList.
This works for me. It returns a boolean.
myEditText.hasFocus()
One thing that you can do is declare a global variable evalue which will tell you which is the last selected EditText by using onTouchListener and then based on the value of evalue, you can set the text value to the edittext by button click. hope you understood.
the code for it can be as follow:
EditText e1,e2;
Button b1,b2;
String evalue;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
e1=(EditText)findViewById(R.id.editText1);
e2=(EditText)findViewById(R.id.editText2);
b1=(Button)findViewById(R.id.button1);
b2=(Button)findViewById(R.id.button2);
e1.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View arg0, MotionEvent arg1)
{
evalue="1";
return false;
}
});
e2.setOnTouchListener(new View.OnTouchListener()
{
public boolean onTouch(View arg0, MotionEvent arg1)
{
evalue="2";
return false;
}
});
b1.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
if(evalue=="1")
{
e1.setText("yes");
}
if(evalue=="2")
{
e2.setText("yes");
}
}
});
b2.setOnClickListener(new View.OnClickListener()
{
public void onClick(View arg0) {
if(evalue=="1")
{
e1.setText("No");
}
if(evalue=="2")
{
e2.setText("No");
}
}
});
}
Its a logical coding.. not upto the mark.. if you find a better one. then use it. thank you.
This worked for me.
e1 = (EditText) findViewById(R.id.editText1);
e1.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View arg0, boolean hasfocus) {
if (hasfocus) {
Log.e("TAG", "e1 focused")
} else {
Log.e("TAG", "e1 not focused")
}
}
});
With Java 8 lambdas:
EditText editTextTo = findViewById(R.id.editTextTo);
editTextTo.setOnFocusChangeListener((view, b) -> {
if (view.isFocused()) {
// Do whatever you want when the EditText is focused
// Example:
editTextFrom.setText("Focused!");
}
});
Note that the view inside the lambda function is actually an instance of an EditText.
Have your Fragment implement OnTouchListener & OnFocusChangeListener:
public class AttributesFragment extends Fragment
implements OnTouchListener, OnFocusChangeListener {
Then implement using:
#Override
public boolean onTouch(View view, MotionEvent event) {
if (view instanceof EditText) {
view.setOnFocusChangeListener(this); // User touched edittext
}
return false;
}
#Override
public void onFocusChange(View v, boolean hasFocus) {
}
Don't forget to set your listener after creating your EditText
editText.setOnTouchListener(this);
This way if an EditText box is focused by default but user has not changed the field it will not fire the onFocusChange event.
Simple Coding:
if(EditText1.isFocused()){
//EditText1 is focused
}else if(EditText2.isFocused()){
//EditText2 is focused
}
This worked for me using Java 8 (lambdas):
EditText myEditText = findViewById(R.id.editText);
myEditText.setOnFocusChangeListener((view, hasFocus) -> {
if(hasFocus){
Log.e("TAG", "myEditext has focus")
}else{
Log.e("TAG", "myEditext has no focus")
}
});
In your activity or fragment implement OnFocusChangeListener.
edittextNeme= (EditText) findViewById(R.id.edittextNeme);
edittextNeme.setOnFocusChangeListener(this);
You will have to check which view changed focus by getting the view id with view.getId() and handle accordingly.
#Override
public void onFocusChange(View view, boolean hasfocus) {
switch(view.getId()){
case R.id.edittextNeme:
//Do something
break;
...etc
}
}
val currentFocusView = activity.currentFocus
if (currentFocusView is EditText){
currentFocusView.appendText("Has Focus!")
}
I am working on my project where I have a listView and each item is a LinaerLayout that has a TextView with Linkify hyperlink.
So, when I press the an item in the List view, it opens a dialog, which is fine.
When I press the linked text in the listView, it opens a dialog, which is fine.
PROBLEM: When I LONG-PRESS the linked text in the Listview, it opens a dialog AND an activity of the given link at the same time! In this case, I only want it to open the dialog only.
In other words, I want to ignore Linkify's hyperlink on Long press.
Does anyone know how I can do this?
I don't know where to apply LongPress attributs... Thanks in advance.
FYI, I tried the following but doesn't work.
public class URLSpanNoUnderline extends URLSpan implements OnLongClickListener {
public URLSpanNoUnderline(String url) {
super(url);
}
#Override
public void updateDrawState(TextPaint textPaint) {
super.updateDrawState(textPaint);
textPaint.setUnderlineText(false);
}
#Override
public void onClick(View v) {}
#Override
public boolean onLongClick(View v) {
Log.d("log", "lonnnnnnnnnnnnnnnng click");
return false;
}
}
you need a longClick mark,set it when in textview longclicklistener,and in touchlistener,when action equals MotionEvent.ACTION_UP and longClick is true,return true。
textview.setOnLongClickListener(new View.OnLongClickListener() {
#Override
public boolean onLongClick(View v) {
isLongClick= true;
return false;
}
});
textview.setOnTouchListener(new View.OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if(event.getAction() == MotionEvent.ACTION_UP && isLongClick){
isLongClick= false;
return true;
}
if(event.getAction() == MotionEvent.ACTION_DOWN){
isLongClick= false;
}
return v.onTouchEvent(event);
}
});
this problem happend in some phone.
How do I know when my edit text is done being edited? Like when the user selects the next box, or presses the done button on the soft keyboard.
I want to know this so I can clamp the input. It looks like text watcher's afterTextChanged happens after each character is entered. I need to do some calculations with the input, so I would like to avoid doing the calculation after each character is entered.
thanks
By using something like this
meditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
switch (actionId){
case EditorInfo.IME_ACTION_DONE:
case EditorInfo.IME_ACTION_NEXT:
case EditorInfo.IME_ACTION_PREVIOUS:
yourcalc();
return true;
}
return false;
}
});
EditText inherits setOnFocusChangeListener which takes an implementation of OnFocusChangeListener.
Implement onFocusChange and there's a boolean parameter for hasFocus. When this is false, you've lost focus to another control.
EDIT
To handle both cases - edit text losing focus OR user clicks "done" button - create a single method that gets called from both listeners.
private void calculate() { ... }
btnDone.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
calculate();
}
});
txtEdit.setOnFocusChangeListener(new OnFocusChangeListener() {
public void onFocusChange(View v, boolean hasFocus) {
if(!hasFocus)
calculate();
}
});
Using an EditText object xml defined like this:
<EditText
android:id="#+id/create_survey_newquestion_editText_minvalue"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_centerVertical="true"
android:ems="4"
android:imeOptions="actionDone"
android:inputType="number" />
We can capture its text i) when the user clicks the Done button on the soft keyboard (OnEditorActionListener) or ii) when the EditText has lost the user focus (OnFocusChangeListener) which now is on another EditText:
/**
* 3. Set the min value EditText listener
*/
editText= (EditText) this.viewGroup.findViewById(R.id.create_survey_newquestion_editText_minvalue);
editText.setOnEditorActionListener(new OnEditorActionListener()
{
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event)
{
String input;
if(actionId == EditorInfo.IME_ACTION_DONE)
{
input= v.getText().toString();
MyActivity.calculate(input);
return true; // consume.
}
return false; // pass on to other listeners.
}
});
editText.setOnFocusChangeListener(new View.OnFocusChangeListener()
{
#Override
public void onFocusChange(View v, boolean hasFocus)
{
String input;
EditText editText;
if(!hasFocus)
{
editText= (EditText) v;
input= editText.getText().toString();
MyActivity.calculate(input);
}
}
});
This works for me. You can hide the soft keyboard after made the calculations using a code like this:
private void hideKeyboard(EditText editText)
{
InputMethodManager imm= (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
Edit: added return values to onEditorAction
I have done this simple thing, when focus is shifted from edit text get the text. This will work if user shifts the focus to select other views like a button or other EditText or any view.
editText.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
EditText editText = (EditText) v;
String text = editText.getText().toString();
}
}
});
To be more highlevel you may use TextWatcher's afterTextChanged() method.