i am trying to show keyboard onclick
but it is not showing automatically (keyboard is in hidden state in manifest)
working but on double click...
here is the source.
search.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
search_friends.setVisibility(View.VISIBLE);
//my_friends.setVisibility(View.GONE);
search_friends.requestFocus();
if(search_friends.hasFocus())
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
}
else
{
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
}
}
});
i want this on single click...
this is my method, I made it for an Util class, I use it in every project and it works:
/**
* For hide ed == null <br/>
* For show ed !=null
*
* #param context
* Activity
* #param ed
* EditText
*/
public static void hideOrShowSoftKeyboard(Activity context, EditText ed) {
try {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(context.INPUT_METHOD_SERVICE);
if (ed != null) {
inputManager.showSoftInput(ed, 0);
} else {
inputManager.hideSoftInputFromWindow(context.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
} catch (NullPointerException e) {
LogService.log(TAG, "NullPointerException");
}
}
// in your implementation
#Override
public void onClick(View v) {
search_friends.setVisibility(View.VISIBLE);
//for showing the keyboard
AppNameUtils.hideOrShowSoftKeyboard(this,search_friends);
}
Related
In my app, I'm making use of AlertDialog instances with custom views that contain text fields, to let the user enter values in a modal dialog.
Problem is, there seems to be no clean, simple, reliable way to make sure the keyboard pops up as the AlertDialog is shown AND disappears again as the dialog is dismissed.
So far I'm using the following to display the keyboard:
// 'dialog' is the AlertDialog instance
Window window = dialog.getWindow();
if (window != null) {
window.setSoftInputMode(SOFT_INPUT_STATE_VISIBLE);
}
dialog.show();
This feels a bit dirty already but works consistently so I can't complain. However, hiding the keyboard again is tricky. For starters, I have the following utility method:
public static void hideKeyboard(Activity activity) {
InputMethodManager imm = getIMM(activity);
IBinder windowToken = activity.getWindow().getDecorView().getWindowToken();
imm.hideSoftInputFromWindow(windowToken, HIDE_IMPLICIT_ONLY);
}
Simply calling that (with the topmost activity as the activity argument) in a button callback of my AlertDialog doesn't work. For the utility method to do what it's intended to, I have to call it after a short delay.
Util.runAfterTimeout(5, () -> Util.hideKeyboard(activity));
(The runAfterTimeout method calls a given Runnable on the main thread looper with the given timeout in milliseconds.)
At this point the code really starts to stink. It gets worse though.
With one of my AlertDialog variants, a timeout of 5 milliseconds works. This is short enough to seem immediate to a human.
Another one of my AlertDialogs needs a higher timeout. It seems to start working around 100ms, at which point the delay starts to become noticable.
(The reason is probably that one of the dialogs uses its own ok/cancel buttons in its custom layout, whereas the other uses setPositiveButton and setNegativeButton. The reasons are layout-related.)
I don't know if these values will work on all devices / in all situations. What if a different CPU or even different load on the same CPU causes the scheduler to act differently, and my hack starts to fail again? Should I up the delay to 200ms to be safe? Maybe to 500ms for very slow devices? (It's very noticable at that point.) Who knows!
I can't imagine this scenario being so rare as to warrant such hacks. I just want to show a popup dialog and let the user enter some value(s) into it.
Anyone know a clean solution? Ditch AlertDialog entirely and use something else maybe? Or will using a DialogFragment maybe solve my pains?
Thanks in advance.
You can check this example. It works fine in fragment and activity.
* #param context of the application
*/
public static void showKeyBoard(Context context) {
try {
InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, InputMethodManager.HIDE_IMPLICIT_ONLY);
}
} catch (Exception e) {
e.printStackTrace();
}
}
/**
* #param context context of the application
* #param contextualView contextual view of the fragment/activity
*/
public static void hideKeyBoard(Context context, View contextualView) {
try {
InputMethodManager imm = (InputMethodManager) context.getSystemService(
Context.INPUT_METHOD_SERVICE);
if (imm != null) {
imm.hideSoftInputFromWindow(contextualView.getWindowToken(), 0);
}
} catch (Exception e) {
e.printStackTrace();
}
}
public void showSingleInput(String title, String previousText, SingleEditTextInput.TextInputListener listener) {
SingleEditTextInput singleEditTextInput = new SingleEditTextInput();
Bundle args = new Bundle();
args.putString("DIALOG_TITLE", title);
args.putString("PREVIOUS_TEXT", previousText);
singleEditTextInput.setArguments(args);
singleEditTextInput.setListener(listener);
singleEditTextInput.show(fragmentManager, POP_UP_DIALOG);
}
public class SingleEditTextInput extends DialogFragment {
private String title = null, previousString = null;
TextInputListener listener;
Context mContext;
private Button btnSubmit;
private Button btnCancel;
EditText editText;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
mContext = getActivity();
AlertDialog.Builder builder = new AlertDialog.Builder(mContext);
AlertDialog alertDialog = builder.create();
alertDialog.setView(initView());
alertDialog.setCanceledOnTouchOutside(false);
btnSubmit.setOnClickListener(view -> {
String input;
input = editText.getText().toString().trim();
if (input!=null) {
hideKeyBoard(mContext, editText.findFocus());
dismiss();
listener.onClickSubmit(input);
} else
ToastMsg.getInstance(getActivity()).Show(getResources().getString(R.string.description_error));
});
btnCancel.setOnClickListener(view -> {
hideKeyBoard(mContext, editText);
dismiss();
});
editText.addTextChangedListener(textWatcher);
return alertDialog;
}
#Override
public void onPause() {
super.onPause();
hideKeyBoard(mContext, editText.findFocus());
}
private TextWatcher textWatcher = new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
if (s.toString().trim().length() > 0) {
btnSubmit.setEnabled(true);
} else {
btnSubmit.setEnabled(false);
}
}
#Override
public void afterTextChanged(Editable s) {
}
};
private View initView() {
View mView;
mView = LayoutInflater.from(mContext).inflate(R.layout.l_single_edittext, null);
TextView tvTitle = mView.findViewById(R.id.tv_dialog_title);
editText = mView.findViewById(R.id.et_input);
btnSubmit = mView.findViewById(R.id.btn_next);
btnSubmit.setText(R.string.ok);
btnCancel = mView.findViewById(R.id.btn_back);
btnCancel.setText(R.string.cancel_text);
if (getArguments() != null) {
title = getArguments().getString("DIALOG_TITLE", "");
previousString = getArguments().getString("PREVIOUS_TEXT", "");
}
if (title!=null) {
tvTitle.setText(title);
}
if (previousString!=null) {
editText.setText(previousString);
}
showKeyBoard(mContext);
return mView;
}
public void setListener(TextInputListener dialogListener) {
this.listener = dialogListener;
}
public interface TextInputListener {
void onClickSubmit(String input);
}
}
If I may to ask almost the same question here from this topic
I've added in my activity_main.xml file:
android:focusable="true"
android:focusableInTouchMode="true"
activity_main.xml:
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
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:layout_width="match_parent"
android:layout_height="match_parent"
android:focusable="true"
android:focusableInTouchMode="true"
tools:context="com.example.stefancvetkovic.stefantest001.MainActivity">
<EditText
android:id="#+id/txtScanedResult"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:ems="10"
android:inputType="textPersonName"
tools:layout_editor_absoluteX="16dp"
tools:layout_editor_absoluteY="16dp" />
</android.support.constraint.ConstraintLayout>
And it works fine, but when I want to hide my keyboard on finish event, the keyboard stays opened.
MainActivity.java:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
((EditText)findViewById(R.id.txtScanedResult)).setOnEditorActionListener(
new EditText.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH ||
actionId == EditorInfo.IME_ACTION_DONE ||
event != null &&
event.getAction() == KeyEvent.ACTION_DOWN &&
event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
if (event == null || !event.isShiftPressed()) {
// the user is done typing.
//HIDE KEYBOARD
EditText edtView=(EditText)findViewById(R.id.txtScanedResult);
edtView.setInputType((InputType.TYPE_NULL));
//
Toast.makeText(getApplicationContext(),"Voila!",Toast.LENGTH_SHORT)
.show();
return true; // consume.
}
}
return false; // pass on to other listeners.
}
});
}
Toast works perfectly on finish event, but keyboard stays opened.
Hoiw can I manage to be initialy closed keyboard on the load, and to be hidden on finishEvent?
I am running in emulator on Android 5.1
Try this one
/**
* This function is used to hide soft keyboard
*
* #param context mContext
* #param view view for which keyboard is open
*/
public static void hideSoftInput(Context context, View view) {
if (view != null) {
InputMethodManager inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
if (!inputMethodManager.isActive()) {
return;
}
inputMethodManager.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
}
/**
* This function is used to hide soft keyboard
*
* #param activity activity
*/
public static void hideSoftInput(Activity activity) {
try {
if (activity != null) {
View focusedView = activity.getCurrentFocus();
hideSoftInput(activity, focusedView);
}
} catch (Throwable t) {
CustomLogHandler.printErrorlog(t);
}
}
/**
* This function is used to show soft keyboard
*
* #param activity activity
*/
public static void showSoftInput(Activity activity) {
try {
if (activity != null) {
View focusedView = activity.getCurrentFocus();
if (focusedView != null) {
InputMethodManager inputMethodManager = (InputMethodManager) activity.getSystemService(Context.INPUT_METHOD_SERVICE);
inputMethodManager.showSoftInput(focusedView, InputMethodManager.SHOW_IMPLICIT);
}
}
} catch (Throwable t) {
CustomLogHandler.printErrorlog(t);
}
}
/**
* This function is used to show soft keyboard
*
* #param view view for which soft keyboard need to be opened
*/
public static void showSoftInput(final View view) {
try {
if (view == null) {
return;
}
view.requestFocus();
InputMethodManager inputManager = (InputMethodManager) view.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.showSoftInput(view, 0);
} catch (Exception e) {
CustomLogHandler.printErrorlog(e);
}
}
or try
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
Call it before showing toast.
public void hideKeyboard(Activity context) {
// Check if no view has focus:
View view = context.getCurrentFocus();
if (view != null) {
InputMethodManager inputManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(view.getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
}
}
Try this code:
/**
* Hides the soft keyboard
*/
public void hideSoftKeyboard() {
if(getCurrentFocus()!=null) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
inputMethodManager.hideSoftInputFromWindow(getCurrentFocus().getWindowToken(), 0);
}
}
/**
* Shows the soft keyboard
*/
public void showSoftKeyboard(View view) {
InputMethodManager inputMethodManager = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
view.requestFocus();
inputMethodManager.showSoftInput(view, 0);
}
or do this:
In the AndroidManifest.xml:
<activity android:name="com.your.package.ActivityName"
android:windowSoftInputMode="stateHidden" />
or try:
getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_HIDDEN);
i am using
com.sothree.slidinguppanel
its working fine but on click listener is not working below is my code
slidingLayout = (SlidingUpPanelLayout) findViewById(R.id.sliding_layout);
slidingLayout.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//my code
}
}
});
so its never going to the my code part i mean its not hitting the on click listener. please help
Because it's already handled in the Library:
/**
* Set the draggable view portion. Use to null, to allow the whole panel to
* be draggable
*
* #param dragView
* A view that will be used to drag the panel.
*/
public void setDragView(View dragView) {
if (mDragView != null) {
mDragView.setOnClickListener(null);
}
mDragView = dragView;
if (mDragView != null) {
mDragView.setClickable(true);
mDragView.setFocusable(false);
mDragView.setFocusableInTouchMode(false);
mDragView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (!isEnabled() || !isTouchEnabled())
return;
if (mSlideState != PanelState.EXPANDED && mSlideState != PanelState.ANCHORED) {
if (mAnchorPoint < 1.0f) {
setPanelState(PanelState.ANCHORED);
} else {
setPanelState(PanelState.EXPANDED);
}
} else {
setPanelState(PanelState.COLLAPSED);
}
}
});
;
}
}
Here all thing is working fine but i want to hide keyboard when click anywhere outside edittext...
Here is the source:
screen = this;
sp = new ServiceProxy();
login_account=(Button)findViewById(R.id.login_button);
sign_up=(Button)findViewById(R.id.button_login_sign_up_link);
login_username=(EditText)findViewById(R.id.login_user_name);
login_pass=(EditText)findViewById(R.id.login_user_password);
/* //this is the thing i want. means i want to hide keyboard onclick outside edittext
relative_layout = (RelativeLayout)findViewById(R.id.login_account);
relative_layout.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
// Hide Keyboard
InputMethodManager imm = (InputMethodManager) UsernameverifyActivity.screen.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(getWindow().getDecorView().getWindowToken(), 0);
return true;
}
});*/
login_account.setOnClickListener(new OnClickListener() {
//private Integer id = 0;
#Override
public void onClick(View v) {
String log_username = login_username.getText().toString();
String log_password = login_pass.getText().toString();
if(log_username.matches("")){
MessageDialog.showMessage("Alert!",
"Please enter Username", LoginAccountActivity.screen);
}
else if(log_password.matches("")){
MessageDialog.showMessage("Alert",
"Please enter Password", LoginAccountActivity.screen);
}
else{
try {
String username = log_username;
String password = log_password;
System.out.println("password is: " + password);
requestFor = "login";
additionalData = new JSONObject();
additionalData.put("username", username);
additionalData.put("password", password);
additionalData.put("is_active", "Y");
} catch (JSONException e) {
e.printStackTrace();
}
hideSoftKeyboard();
PostTask pt = new PostTask();
pt.execute(screen);
pdialog = new ProgressDialog(LoginAccountActivity.this);
pdialog.setCancelable(false);
pdialog.setMessage("Please Wait...");
pdialog.show();
}
}
private void hideSoftKeyboard() {
if(getCurrentFocus()!=null && getCurrentFocus() instanceof EditText){
InputMethodManager imm = (InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(login_username.getWindowToken(), 0);
imm.hideSoftInputFromWindow(login_pass.getWindowToken(), 1);
}
}
});
sign_up.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Intent i=new Intent(getApplicationContext(),CreateAccountActivity.class);
startActivity(i);
overridePendingTransition(R.anim.animation,R.anim.animation2);
finish();
}
});
}
private class PostTask extends AsyncTask<Activity, String, String>
{
#Override
protected String doInBackground(Activity... params) {
if(requestFor.equals("login"))
return (sp.login(params[0]));
//return true;
else
System.out.println("Else Case" +LoginAccountActivity.screen.requestFor);
return "";
}
protected void onPostExecute(String result) {
if (requestFor.equals("login")) {
if (result.equals("true")) {
if(pdialog != null)
{
pdialog.setCancelable(true);
pdialog.dismiss();
}
Intent i=new Intent(getApplicationContext(),MainActivity.class);
startActivity(i);
startActivity(i);
overridePendingTransition(R.anim.animation,R.anim.animation2);
finish();
}
else{
pdialog.setCancelable(true);
pdialog.dismiss();
MessageDialog.showMessage("Alert",
"Incorrect Username or Password", LoginAccountActivity.screen);
}
}
}
}
Update:
I have the following error:
Null Pointer Exception in LOG internalPolicy.phonewindowDecorView
At this line on Text_chat Activity:
InputMethodManager imm = (InputMethodManager) Text_chat.screen.getApplicationContext().getSystemService(Context.INPUT_METHOD_SERVICE);
clearFocus method with a "fake" container might be a solution.
You should create an empty view which is focusable like the following:
<LinearLayout
android:id="#+id/container"
... >
<LinearLayout
android:layout_width="0dip" android:layout_height="0dip"
android:orientation="vertical"
android:focusableInTouchMode="true" android:focusable="true" />
<EditText
... >
<EditText
... >
</LinearLayout>
Then, put the following code in your onCreate method when you click outside in your layout:
// init your InputMethodManager outside onCreate method:
InputMethodManager mImm;
//...
// in onCreate:
mImm = (InputMethodManager) getActivity().getSystemService(Context.INPUT_METHOD_SERVICE);
// on click event to hide the keyboard:
((LinearLayout) findViewById(R.id.container)).setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(edittext1.hasFocus() || edittext2.hasFocus() || ...)
hideSoftKeyboard();
}
});
So hideSoftKeyboard method might be:
private void hideKeyboard() {
mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
getActivity().getCurrentFocus().clearFocus();
}
The clearFocus method when it's called, reset the focus on the first view which have focusable attributes set to true in your layout and hideSoftInputWindow with the second param set 0 force the keyboard to hide. So your EditText lose the focus and the SoftKeyboard disappears.
I found a similar trick here: How to hide soft keyboard on android after clicking outside EditText? (and another answer but I can't find it) and it works well!
Alternative: to reset the focus at the same time
private void hideKeyboard() {
mImm.hideSoftInputFromWindow(getActivity().getCurrentFocus().getWindowToken(), 0);
// set the focus to the container:
((LinearLayout) findViewById(R.id.container)).requestFocus();
}
Let me know if this helps.
try this one...
put it below code in your activity in oncreate method and onpause, onresume.
if you want to hidden your softkeyboard try below lines in oncreate ,onpause,onresume in which are the activity you have to perform hidden keyboard.
it will works..
this.getWindow().setSoftInputMode(
WindowManager.LayoutParams.SOFT_INPUT_STATE_ALWAYS_HIDDEN);
put .xml file in edittext properties like
android:focusableInTouchMode="true"
so call your hideSoftKeyboard() method in onCreate() in side..
like
oncreate()
{
hideSoftKeyboard();
}
thank you..
For some EditText views I want to use a custom keyboard instead of the soft one.
The problem is when I click on an EditText for the first time both keyboards are shown. When I click for the second time - the soft keyboard finally disappeares.
What might be the reason for such behavior?
Here's the code I use:
package pkleczek.profiwan.keyboards;
import android.app.Activity;
import android.inputmethodservice.KeyboardView;
import android.text.InputType;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.View.OnFocusChangeListener;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
public abstract class CustomKeyboard {
/** A link to the KeyboardView that is used to render this CustomKeyboard. */
protected KeyboardView mKeyboardView;
/** A link to the activity that hosts the {#link #mKeyboardView}. */
protected Activity mHostActivity;
/** Returns whether the CustomKeyboard is visible. */
public boolean isCustomKeyboardVisible() {
return mKeyboardView.getVisibility() == View.VISIBLE;
}
/**
* Make the CustomKeyboard visible, and hide the system keyboard for view v.
*/
public void showCustomKeyboard(View v) {
mKeyboardView.setVisibility(View.VISIBLE);
mKeyboardView.setEnabled(true);
if (v != null) {
InputMethodManager inputManager = (InputMethodManager) mHostActivity
.getSystemService(Activity.INPUT_METHOD_SERVICE);
inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
}
/** Make the CustomKeyboard invisible. */
public void hideCustomKeyboard() {
mKeyboardView.setVisibility(View.GONE);
mKeyboardView.setEnabled(false);
}
/**
* Register <var>EditText<var> with resource id <var>resid</var> (on the
* hosting activity) for using this custom keyboard.
*
* #param resid
* The resource id of the EditText that registers to the custom
* keyboard.
*/
public void registerEditText(int resid) {
EditText edittext = (EditText) mHostActivity.findViewById(resid);
edittext.setOnFocusChangeListener(new OnFocusChangeListener() {
#Override
public void onFocusChange(View v, boolean hasFocus) {
if (hasFocus) {
showCustomKeyboard(v);
} else {
hideCustomKeyboard();
}
}
});
edittext.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
showCustomKeyboard(v);
}
});
edittext.setInputType(edittext.getInputType()
| InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS);
}
}
Try to put the following condition in your InputMethodManager code before inputManager.hideSoftInputFromWindow(v.getWindowToken(), 0);line:
if (inputManager!=null) {
Activity activity = getActivity();
if (acvivity == null)
return;
if (activity.getCurrentFocus() == null)
return;
if (activity.getCurrentFocus().getWindowToken() == null)
return;
inputManager.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), 0);
}
I used it in ListFragment to hide the default keyboard. First when i press an EditText and keyboard is shown and when on onScrollStateChanged i hide it.
You can also try to put the InputMethodManager code inside the onClickListener of the EditText and then call your showCustomKeyboard() method.
Put an Else statement and Log in it after the if (v != null), maybe your View v is null.
The solution provided by Rotemmiz in the topic Close/hide the Android Soft Keyboard worked for me.
An abstract:
public void setEditTextFocus(EditText editText, boolean isFocused)
{
editText.setCursorVisible(isFocused);
editText.setFocusable(isFocused);
editText.setFocusableInTouchMode(isFocused);
if (isFocused)
{
editText.requestFocus();
}
}