close keyboard when user taps on recyclerView - android

I have a RecyclerView and below there's an EditText. I want when user taps outside the EditText to close the keyboard.
I searched and find this answer here but it doesn't work for me. User taps outside but EditText still has focus.
My XML code is :
<android.support.v7.widget.RecyclerView
android:id="#+id/rv_chatroom_messages_list"
android:paddingBottom="#dimen/spacing_medium"
android:layout_weight="1"
android:clickable="true" android:focusableInTouchMode="true" android:focusable="true"
android:layout_width="match_parent" android:layout_height="0dp"/>
<LinearLayout
android:orientation="horizontal"
android:background="#color/white"
android:layout_marginLeft="#dimen/spacing_large" android:layout_marginBottom="#dimen/spacing_medium"
android:layout_marginRight="#dimen/spacing_large" android:paddingRight="#dimen/spacing_medium"
android:layout_width="match_parent" android:layout_height="wrap_content">
<EditText
android:id="#+id/et_chatroom_send_message"
android:layout_gravity="bottom"
android:background="#null"
android:textSize="#dimen/app_text_size_normal" android:hint="Type to reply"
android:layout_marginLeft="#dimen/spacing_large" android:layout_marginRight="#dimen/spacing_large"
android:layout_weight="1"
android:layout_width="0dp" android:layout_height="#dimen/spacing_xlarge" android:inputType="textMultiLine" />
<ImageView
android:id="#+id/iv_chatroom_send_message_btn"
android:src="#drawable/ic_pong_2"
android:layout_gravity="center"
android:layout_width="48dp" android:layout_height="48dp" android:contentDescription="Send msg button" />
</LinearLayout>

Simply set an onTouchListener() to your RecyclerView and call the hideKeyboard() method from it.

close it when your editText losses it's focus.
like that:
EditText editText = (EditText) findViewById(R.id.edittxt);
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (!hasFocus) {
// code to execute when EditText loses focus
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(editText.getWindowToken(), 0);
}
}
});

Call this method on recyclerview touch listener...
public static void hideKeyboard(final Activity activity) {
final View view = activity.getCurrentFocus();
final InputMethodManager imm = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
Handler handler = new Handler();
handler.postDelayed(new Runnable() {
#Override
public void run() {
if (view == null) {
View view2 = new View(activity);
imm.hideSoftInputFromWindow(view2.getWindowToken(), 0);
} else {
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
}, 125);
}

Related

How to clear focus from edittext when the keyboard closes after click back button?

I have an AppBarLayout and I hide when I touch EditText.
SearchFragment.class
binding.searchEt.setOnFocusChangeListener { view, hasFocus ->
if (hasFocus) {
binding.appBarLayout.setExpanded(false, true)
} else {
binding.appBarLayout.setExpanded(true, true)
}
}
But I can't show again AppBarLayout when keyboard closes. Because when keyboard closes EditText focus does not change.
Xml
<EditText
android:id="#+id/searchEt"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_marginStart="8dp"
android:layout_toStartOf="#+id/close_button"
android:layout_toEndOf="#+id/ic_search"
android:background="#android:color/transparent"
android:focusable="true"
android:focusableInTouchMode="true"
android:fontFamily="#font/catamaran_bold"
android:hint="#string/search_hint"
android:imeOptions="actionSearch"
android:includeFontPadding="true"
android:orientation="vertical"
android:paddingStart="12dp"
android:singleLine="true"
android:textAlignment="viewStart"
android:textColor="#000"
android:textDirection="locale"
android:textSize="18dp"
tools:text="alskjfdn" />
How can I clear focus when keyboard hide? Cursor still showing after keyboard hidden.
use something like this:
public void hideKeyboard(Activity activity){
InputMethodManager imm = (InputMethodManager) activity.getSystemService(Activity.INPUT_METHOD_SERVICE);
View view = activity.getCurrentFocus();
if(view != null){
view.clearFocus();
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
inside the keyboard close listener, after close keyboard clear focus from editText
editText.setFocusable(false);
editText.setFocusableInTouchMode(true);

Add layout at bottom with edit text on it and hide it if the edit text is not focused

How to add layout at bottom with edit text on it when pressed button "plus" and hide the layout if the edit text is not focused
please look at this picture example
Add OnFocusChangeListener to the EditText and inside the Overrided onFocusChange(View v, boolean hasFocus) method add or remove your layout based on hasFocus value (its true if it has focus).
Refer this for more on OnFocusChangeListener
Your layout must have a ListView, an EditText, and a FloatingActionButton. Place all these within a RelativeLayout. An example of this would be
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/activity_main"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="abcd.MainActivity">
<android.support.design.widget.FloatingActionButton
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:clickable="true"
android:id="#+id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentEnd="true"/>
<android.support.design.widget.TextInputLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_toLeftOf="#id/fab"
android:layout_alignParentBottom="true"
android:layout_alignParentStart="true">
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="Input"
android:id="#+id/input"
/>
</android.support.design.widget.TextInputLayout>
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentTop="true"
android:layout_alignParentStart="true"
android:layout_above="#id/fab"
android:divider="#android:color/transparent"
android:id="#+id/list"/>
</RelativeLayout>
The back button by default does the function of closing the TextInputLayout. To close it on touching it outside, you can add the following to your activity.
#Override
public boolean dispatchTouchEvent(MotionEvent event) {
if (event.getAction() == MotionEvent.ACTION_DOWN) {
View v = getCurrentFocus();
if ( v instanceof EditText) {
Rect outRect = new Rect();
v.getGlobalVisibleRect(outRect);
if (!outRect.contains((int)event.getRawX(), (int)event.getRawY())) {
v.clearFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
}
return super.dispatchTouchEvent( event );
}

EditText doen't open keyboard in popup

This layout is used for popup window to change name of a textview.But the edittext doesnt show keyboard even on clicking the edittext. I'm using it in a fragment. fragment has a namefield which is meant to be changed on clicking OK in this popup.
This is the xml file for popup window.
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#fff">
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:layout_alignParentBottom="true"
android:id="#+id/name_status_btns"
>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:elevation="2dp"
android:background="#fff"
android:text="CANCEL"
android:textSize="18sp"
android:textColor="#000"
android:id="#+id/cancel_change_name"/>
<TextView
android:layout_width="1dp"
android:layout_height="match_parent"
android:background="#b1b0b0"/>
<Button
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:text="OK"
android:textColor="#000"
android:textSize="18sp"
android:elevation="2dp"
android:background="#fff"
android:id="#+id/ok_change_name"
/>
</LinearLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#b1b0b0"
android:layout_above="#id/name_status_btns"
android:id="#+id/name_status_horizontal_liner"/>
<RelativeLayout
android:layout_width="match_parent"
android:layout_height="60dp"
android:layout_marginTop="15dp"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
android:id="#+id/name_status_edit_field">
<EditText
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="5"
android:hint="write your name here"
android:scrollHorizontally="true"
android:id="#+id/change_name"
android:focusable="true"
android:focusableInTouchMode="true"/>
</RelativeLayout>
<TextView
android:layout_width="match_parent"
android:layout_height="1dp"
android:background="#color/mainColor"
android:layout_below="#id/name_status_edit_field"
android:layout_marginLeft="15dp"
android:layout_marginRight="15dp"
/>
</RelativeLayout>
This is the java file for above xml.
public class Name_Status extends AppCompatActivity implements View.OnClickListener {
EditText name_change;
RelativeLayout name_status_edit_field;
String name;
Button cancel_name_change , ok_name_change;
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.name_status);
DisplayMetrics dm=new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(dm);
int width=dm.widthPixels;
int height=dm.heightPixels;
getWindow().setLayout((int)(width*.8),(int)(height*.3));
name_change=(EditText)findViewById(R.id.change_name);
name_status_edit_field=(RelativeLayout)findViewById(R.id.name_status_edit_field);
name=name_change.getText().toString();
cancel_name_change=(Button)findViewById(R.id.cancel_change_name);
ok_name_change=(Button)findViewById(R.id.ok_change_name);
ok_name_change.setOnClickListener(this);
name_change.setOnClickListener(this);
name_status_edit_field.clearFocus();
name_change.setFocusable(true);
//name_change.update();
}
#Override
public void onClick(View v) {
if(v.getId()==R.id.ok_change_name)
{FragActivity1 obj=new FragActivity1();
obj.changeName(name);
Intent intent=new Intent();
intent.setClass(Name_Status.this , MainActivity.class);
startActivity(intent);}
if(v.getId()==R.id.change_name)
{
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInputFromWindow(name_change.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
}
}
}
The main problem is your EditText has a 0dp width and a layout_weight attribute in a RelativeLayout, which does not make any sense.
Either make the parent of the EditText a LinearLayout or remove the layout_weight attribute from the EditText and give it a proper width:
<EditText
android:id="#+id/change_name"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="write your name here"
android:scrollHorizontally="true"
android:focusable="true"
android:focusableInTouchMode="true"/>
The following code is completely unnecessary, you should just remove it from onClick():
if(v.getId()==R.id.change_name)
{
InputMethodManager imm = (InputMethodManager) getSystemService(Context.
INPUT_METHOD_SERVICE);
imm.toggleSoftInputFromWindow(name_change.getApplicationWindowToken(),
InputMethodManager.SHOW_FORCED, 0);
}
You can also try the following for EditText
editText.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(final View v, final boolean hasFocus) {
if (hasFocus && editText.isEnabled() && editText.isFocusable())
editText.post(new Runnable() {
#Override
public void run() {
final InputMethodManager imm = (InputMethodManager) context
.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(editText, InputMethodManager.SHOW_IMPLICIT);
}
});
}
});
For more details refer Keyboard not shown when i click on edittextview in android?
EditText is not suppose to have 0dp width and layout_weight inside a RelativeLayout. Weight works inside LinearLayout. So change your EditText to below:
<EditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:hint="write your name here"
android:scrollHorizontally="true"
android:id="#+id/change_name"
android:focusable="true"
android:focusableInTouchMode="true"/>
And change your OnClick to because EditText will take care of click by itself:
#Override
public void onClick(View v) {
if(v.getId()==R.id.ok_change_name){
FragActivity1 obj=new FragActivity1();
obj.changeName(name);
Intent intent=new Intent();
intent.setClass(Name_Status.this , MainActivity.class);
startActivity(intent);
}
}
And finally remove the below line from your OnCreate() method:
name_change.setOnClickListener(this);
Because EditText will open keyboard by itself when clicked.

Soft keyboard not open in android [duplicate]

This question already has answers here:
Android: softkeyboard not showing up
(5 answers)
Closed 6 years ago.
I am newbie to android and working on a demo app,In that i am having an activity contains an edittext at the top of the screen and want to show the keyboard on the start of that activity i have tried many ways but none of this works,Can anybudy help me to sort it ot?
layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/linearLayout"
android:orientation="vertical" >
<RelativeLayout
android:id="#+id/rl_hdr"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:background="#16BBA1"
android:gravity="center_vertical"
android:padding="10dp">
<ImageView
android:id="#+id/iv_back"
android:layout_width="25dp"
android:layout_height="22dp"
android:layout_alignParentLeft="true"
android:layout_centerVertical="true"
android:layout_marginLeft="0dp"
android:src="#drawable/ic_back_white" />
<EditText
android:layout_width="fill_parent"
android:layout_height="40dp"
android:textColorHint="#939393"
android:singleLine="true"
android:layout_centerInParent="true"
android:hint="Search"
android:layout_marginLeft="5dp"
android:padding="5dp"
android:gravity="center_vertical"
android:drawablePadding="5dp"
android:layout_marginRight="5dp"
android:textSize="16dp"
android:imeOptions="actionDone"
android:cursorVisible="true"
android:layout_toRightOf="#+id/iv_back"
android:drawableRight="#drawable/ic_search"
android:background="#drawable/bg_et_actionbar"
android:id="#+id/et_search" />
</RelativeLayout>
<FrameLayout
android:id="#+id/fragmentTimeline"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_alignParentBottom="true"
android:layout_marginTop="0dp" />
</LinearLayout>
manifest.xml
<activity
android:name="one.tusk.stush.SearchPostActivity"
android:label="Back"
android:parentActivityName="one.tusk.stush.activities.MainActivity"
android:screenOrientation="portrait"
android:windowSoftInputMode="stateAlwaysVisible" >
>
</activity>
SerachPostActivity.java
public class SearchPostActivity extends FragmentActivity implements OnQueryTextListener, OnItemClickListener {
public EditText et_search;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.search_post);
.
.
.
.
et_search = (EditText)findViewById(R.id.et_search);
InputMethodManager inputMethodManager=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.toggleSoftInputFromWindow(linearLayout.getApplicationWindowToken(), InputMethodManager.SHOW_FORCED, 0);
et_search.setOnEditorActionListener(new TextView.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("Done pressed", "Enter pressed");
search.searchPost(et_search.getText().toString().trim());
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return false;
}
});
et_search.setOnFocusChangeListener(new View.OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(et_search, InputMethodManager.SHOW_FORCED);
} else {
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
});
You have to give focus to EditText.Try
android:focusable="true"
in your EditText and it will open the soft keyboard.
Try changing your manifest to
android:windowSoftInputMode="stateVisible"
instead of
android:windowSoftInputMode="stateAlwaysVisible".
If problem persists,try opening it programatically using
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(mEditText, 0);
You may also refer This answer on SO

Hide Keyboard for AutoCompleteTextView

I have two EditText and two AutoCompleteTextView in my layout.
But I like to hide the keyboard only for the AutoCompleteTextView.
But it does not hide the keyboard and when I touch the AutoCompleteTextView, Keyboard still appear, how can I hide the keyboard?
I implemented as
final View addView = getLayoutInflater().inflate(R.layout.addnewtracker, null);
final TrackerInfo newInfo = new TrackerInfo();
String[] type = {"Vehicle", "Person", "Pet", "Others"};
final AutoCompleteTextView actvtype1 = (AutoCompleteTextView) addView.findViewById(R.id.autoCompleteTextView1);
ArrayAdapter<String> typeadapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_multiple_choice,type);
actvtype1.setThreshold(1);
actvtype1.setAdapter(typeadapter);
actvtype1.setTextColor(Color.BLACK);
String[] model = {"TS102", "TS103"};
final AutoCompleteTextView actvtype2 = (AutoCompleteTextView) addView.findViewById(R.id.autoCompleteTextView2);
ArrayAdapter<String> modeladapter = new ArrayAdapter<String>(mContext, android.R.layout.simple_list_item_multiple_choice,model);
actvtype2.setThreshold(1);
actvtype2.setAdapter(modeladapter);
actvtype2.setTextColor(Color.BLACK);
final AlertDialog.Builder alert = new AlertDialog.Builder(this).setTitle("New Tracker").setView(addView);
InputMethodManager keyboard = (InputMethodManager)
getSystemService(Context.INPUT_METHOD_SERVICE);
keyboard.hideSoftInputFromInputMethod(actvtype1.getWindowToken(), 0);
keyboard.hideSoftInputFromInputMethod(actvtype2.getWindowToken(), 0);
alert.setPositiveButton("ADD", new DialogInterface.OnClickListener()
{
#SuppressLint("SimpleDateFormat")
public void onClick(DialogInterface dialog, int whichButton)
{
}
}).setNegativeButton("Cancel", null).show();
My layout is as follow
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
tools:context=".MainActivity" >
<TextView
android:id="#+id/IDnumber"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/IDnumber" />
<EditText
android:id="#+id/IDeditText"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text">
<requestFocus />
</EditText>
<TextView
android:id="#+id/SimCardNum"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Sim_card_number" />
<EditText
android:id="#+id/SimCardEdit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="text"
/>
<TextView
android:id="#+id/description"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/description" />
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:dropDownHeight="100dp"
android:text=""/>
<TextView
android:id="#+id/model"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="#string/Tracker_model"
/>
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView2"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:ems="10"
android:dropDownHeight="100dp"
android:text=""/>
</LinearLayout>
I'm not sure if this is exactly what you're looking for but this is the code that is used to force the keyboard from popping up at the bottom of the screen:
actvtype1.setInputType(InputType.TYPE_NULL);
This will definitely stop the keyboard appearing when you click on that TextView. Hope it helps!
Request for the focus on autotext as :
<AutoCompleteTextView
android:id="#+id/autoCompleteTextView2"
..
.../>
<requestFocus />
And then use this code:
if(autocomplete.hasfocus()){
hideSoftKeyboard();
}
private void hideSoftKeyboard() {
if(getCurrentFocus()!=null && getCurrentFocus() instanceof EditText)
{
InputMethodManager imm =(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getCurrentFocus().getWindowToken(), 0);
}
}
To hide keyboard from onItemClick after clicking on list item in AutoCompleteTextView
public void onItemClick(AdapterView<?> adapterViewIn, View viewIn, int indexSelected, long arg3) {
InputMethodManager imm = (InputMethodManager) getSystemService(viewIn.getContext().INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(viewIn.getApplicationWindowToken(), 0);
// whatever else should be done
}
use this code in your Autocomplete TextView onClick
YourClass.this.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);

Categories

Resources