Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

android edittext remove focus after clicking a button

Tags:

I have an Activity with an EditText and a Button. When the User clicks on the EditText, the keyboard is shown and he can type in some Text - fine. But when the user clicks on the Button I want the EditText to be no more in focus i.e. the keyboard hides til the user clicks again on the EditText.

What can I do to 'hide the focus' of the EditText, after the Button is clicked. Some Code I can add in the OnClick Method of the Button to do that?

EDIT:

<LinearLayout      android:layout_width="fill_parent"     android:layout_height="wrap_content"     android:orientation="horizontal" >      <EditText          android:id="@+id/edt_SearchDest"         android:layout_width="0dip"         android:layout_height="wrap_content"         android:layout_weight="0.8"         android:textSize="18sp"         android:hint="Enter your look-up here.." />      <Button         android:id="@+id/btn_SearchDest"         android:layout_width="0dip"         android:layout_height="wrap_content"         android:layout_weight="0.2"         android:text="Search" />  </LinearLayout> 

Best Regards

like image 351
MojioMS Avatar asked Aug 24 '13 04:08

MojioMS


People also ask

How to remove focus EditText Android?

It's fine if it worked for you, I solved it with android:focusable="true" android:focusableInTouchMode="true" in the parent RelativeLayout. This answer totally worked for me, removing focus of editText AND closing keyboard.

How do you make EditText lose focus?

setOnClickListener(saveButtonListener); private OnClickListener saveButtonListener = new OnClickListener() { @Override public void onClick(View v) { Text1. clearFocus(); Text2. clearFocus(); findViewById(R. id.


1 Answers

Put this in your button listener:

InputMethodManager inputManager = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);   inputManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(),InputMethodManager.HIDE_NOT_ALWAYS); 

EDIT

The solution above will break your app if no EditText is focused on. Modify your code like this:

add this method to you class:

public static void hideSoftKeyboard (Activity activity, View view)  {     InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);     imm.hideSoftInputFromWindow(view.getApplicationWindowToken(), 0); } 

Then, in your button listener, call the method like this:

hideSoftKeyboard(MainActivity.this, v); // MainActivity is the name of the class and v is the View parameter used in the button listener method onClick. 
like image 113
Michael Yaworski Avatar answered Oct 01 '22 05:10

Michael Yaworski