Android lollipop can`t get keyboard input - android

I have user keyboard input working on all android versions except on Android Lollipop (5.0).
I have used this to open software keyboard:
public static void OpenKeyBoard(){
MainActivity._Instance.runOnUiThread(new Runnable() {
public void run() {
InputMethodManager imm = (InputMethodManager) MainActivity._Instance.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(MainActivity._Instance.getWindow().getDecorView(), 0);
}
});
}
and i get user input by standard event :
#Override
public boolean onKeyDown(int keyCode, KeyEvent event)
{
I have this code working for all pre Lollipop versions of Android. When I use it on Lollipop, the software keyboard appears, but when I try to click on any letter/number, the keyboard disappears and the method "onKeyDown" doesn`t receive any keycode.
Did anyone had this problem? Any opinion how to solve this?
Thank you.

Try updating your google SDK to the latest, I did and this fixed any issues I have with the keyboard dismissing.

I has this problem too. I managed to solve this by overriding the onLayout, onFocusChanged & onCheckIsTextEditor methods inside WebView. Here's the code that made it work (I generate a webview programmatically):
this.webView = new WebView(context)
{
boolean layoutChangedOnce = false;
#Override
protected void onLayout(boolean changed, int l, int t, int r, int b)
{
if (!layoutChangedOnce)
{
super.onLayout(changed, l, t, r, b);
layoutChangedOnce = true;
}
}
#Override
protected void onFocusChanged(boolean focused, int direction, Rect previouslyFocusedRect)
{
super.onFocusChanged(true, direction, previouslyFocusedRect);
}
#Override
public boolean onCheckIsTextEditor()
{
return true;
}
};
this.webView.setFocusable(true);
this.webView.setFocusableInTouchMode(true);
this.webView.requestFocus(View.FOCUS_DOWN);
addView(this.webView);

this issue is not limited to just android applications but also occurs when any keyboard related event is accessed using javascript or jquery within a phone browser.
eg. I have my website which asks a user to enter zip code(numeric characters) on a certain page. Now the problem is when up tap on the input box, the numeric keyboard appears but it allows you to paste alpha-numeric characters in it as well.
Reason searched so far,
Try accessing this through your desktop and also a mobile device running android OS 5.0+ and try different possible keystrokes.
Note:
When you enter any alpha-characters using mobile device with above
mentioned configuration it shows up '229' as the keycode.
When you enter any alpha-characters using a desktop it shows up the
appropriate keycode.

This works for me I have a SurfaceView implements SurfaceHolder.Callback with a thread to do drawing
#Override
public boolean onTouchEvent(MotionEvent event)
{
synchronized (this)
{
mouse.useEvent(event);
}
return true;
}
#Override
public InputConnection onCreateInputConnection(EditorInfo editorinfo) {
BaseInputConnection bic = new BaseInputConnection(this, false);
editorinfo.actionLabel = null;
editorinfo.inputType = InputType.TYPE_NULL;
editorinfo.imeOptions = EditorInfo.IME_FLAG_NO_FULLSCREEN;
bic.finishComposingText();
return bic;
}
#Override
public boolean dispatchKeyEvent(KeyEvent event)
{
input.useEvent(event);
return super.dispatchKeyEvent(event);
}

I have solved this using AlertDialog editText programmatically. Eg:
public void KeyboardTextField(int id){
if (id == 0){
final String title = getStringResourceByName("profile_title");
final String createP = getStringResourceByName("profile_confirm");
final String cancel = getStringResourceByName("profile_cancel");
MainActivity._Instance.ActivityWillBeShown = true;
MainActivity._Instance.runOnUiThread(new Runnable() {
public void run() {
AlertDialog.Builder alert = new AlertDialog.Builder(MainActivity._Instance);
alert.setCancelable(false);
alert.setTitle(title);
// alert.setMessage(""); // message
// Set an EditText view to get user input
final EditText input = new EditText(MainActivity._Instance);
final int maxLength = 12;
input.setFilters(new InputFilter[] {new InputFilter() {
#Override
public CharSequence filter(CharSequence source, int start, int end,
Spanned dest, int dstart, int dend) {
if (source != null && blockCharacterSet.contains(("" + source))) {
return "";
}
// TODO Auto-generated method stub
return null;
}
} , new InputFilter.LengthFilter(maxLength)});
//input.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_CLASS_NUMBER);
input.setInputType(InputType.TYPE_TEXT_FLAG_NO_SUGGESTIONS); //turn off txt auto complete
input.setInputType(InputType.TYPE_TEXT_VARIATION_POSTAL_ADDRESS); // type only text,numbers and some special char
alert.setView(input);
//input.setText("Player");
alert.setPositiveButton(createP, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText().toString();
// Do something with value!
if (value.isEmpty()){
value = "Player";
}
nativeName(value);
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
});
alert.setNegativeButton(cancel, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
InputMethodManager imm = (InputMethodManager)getSystemService(
Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(input.getWindowToken(), 0);
}
});
alert.show();
};
});
}
And Whenever you need keyboard you just call this function. It works on all Android versions (4.x, 5.x, 6.0)

Related

Show/hide keyboard together with AlertDialog

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);
}
}

(Android)How to clear keyboard memory in certain situation(Acer Keyboard)

In the first place, Thank everyone for coming in and sorry for my poor English, So I describe this situation directly,
I develop with SONY, When I clicked the clear button in EditText, it's working normally!, even I use others phone, like HTC, Oppo,mi.. All's well!
After that I tried to install it in Acer, the clear button still working,
BUT!!!!!
After I clicked the clear button, Next use keyboard again, the data of my first input still here.
The data of my first input.
So, "MyFirstData" will still appear when I input again like
Second-time input situation
I was really confused because I have no idea how to fix it.
So what can I do, clear keyboard data? How?
many thanks!!!!
Code here:
binding.searchView is my editext
binding.searchView.addTextChangedListener(new TextWatcherAdapter());
binding.searchView.setOnEditorActionListener(getSearchEditListener());
channelDialogHelper = new ChannelDialogHelper(this);
}
private TextView.OnEditorActionListener getSearchEditListener() {
return new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
messageResultAdapter.clearAdapter();
shareFileResultAdapter.clearAdapter();
keyword = MessageFactory.getInstance().parseSourceData(v.getText().toString());
if (StringUtil.isEmpty(keyword)) {
return false;
}
hasMessageResult = false;
hasFileResult = false;
if (binding.searchMessageButton.isSelected()) {
searchMessageListener(binding.searchMessageButton);
} else if (binding.searchFileButton.isSelected()) {
searchFileListener(binding.searchFileButton);
}
return true;
}
return false;
}
};
}
TextWatcherAdapter:
public class TextWatcherAdapter implements TextWatcher {
public TextWatcherAdapter() {
}
public void beforeTextChanged(CharSequence var1, int var2, int var3, int var4) {
}
public void onTextChanged(CharSequence var1, int var2, int var3, int var4) {
}
public void afterTextChanged(Editable var1) {
}
}
One possible solution is to remove the exact word(s) using ContentResolver.delete(). Example:
private int deleteWord(String word) {
if (TextUtils.isEmpty(word)) {
return -1;
}
return getContentResolver().delete(UserDictionary.Words.CONTENT_URI,
UserDictionary.Words.WORD + "=?", new String[] { word });
}
And of course, need
<uses-permission android:name="android.permission.WRITE_USER_DICTIONARY" />
defined in the manifest.
Hope this helps.

EditText not adding space after word swiped in

I have an android phone using googles keyboard. On any EditText field in any other app if I use the swipe method to enter text in, it adds a space after each word. However, I have written my own app and when I use the swipe method to enter text on my EditText field it does NOT add a space sothewordsbleedtogether. This is very annoying.
I have an AlertDialog with a linear view added. On that linear view there is a text EditText. Here is my code to create the EditText and add it to the view:
final EditText titleBox = new EditText(this);
titleBox.setInputType(InputType.TYPE_TEXT_FLAG_AUTO_CORRECT |
InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_FLAG_CAP_SENTENCES |
InputType.TYPE_TEXT_VARIATION_SHORT_MESSAGE);
titleBox.setHint("Title");
layout.addView(titleBox);
Any ideas why its not adding spaces in between my words?
This was marked as a possible duplicate, but that question was about not allowing the first character to be a space....Im asking about allowing a space after words that are entered via a keyboard swipe.
Update
Here is the entire method of similar page, its having the same issue, its slightly less complex then the initial page I was troubleshooting. This one doesn't even have a LinearLayout associated:
private void addBudget(final Budget budget) {
EditText taskEditText = new EditText(this);
taskEditText.setId(R.id.add_budget_text);
taskEditText.setInputType(InputType.TYPE_TEXT_FLAG_CAP_SENTENCES);
String dialogTitle = "Add budget";
final AlertDialog dialog = new AlertDialog.Builder(this)
.setTitle(dialogTitle)
.setMessage("What do you want to call this budget?")
.setView(taskEditText)
.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// final String task = ;
SQLiteDatabase db = mHelper.getWritableDatabase();
Budget lBudget = new Budget();
if (budget != null) {
lBudget = budget;
}
EditText taskEditText = (EditText) findViewById(R.id.add_budget_text);
lBudget.title = String.valueOf(taskEditText.getText());
// Init custom budget object //new Budget(){{ title=task; id = budgetID;}}
int retId = mHelper.saveBudget(db, lBudget);
db.close();
int retRow = updateUI(retId);
mTaskListView.smoothScrollToPosition(retRow);
}
})
.setNegativeButton("Cancel", null)
.create();
// Handle done on soft keyboard
taskEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
int result = actionId & EditorInfo.IME_MASK_ACTION;
if (result == EditorInfo.IME_ACTION_DONE) {
dialog.getButton(DialogInterface.BUTTON_POSITIVE).performClick();
return true;
}
return false;
}
});
dialog.getWindow().setSoftInputMode(WindowManager.LayoutParams.SOFT_INPUT_STATE_VISIBLE);
dialog.show();
}
I didnt know if you got solved, i just had the same problem today and found a way to solve it.
I saw a "extrange" performance of the swipe, sometimes it showed the "blankspace" and sometimes not.
The way i found to check if it was shown and if it didnt, add it, was this:
editText.addTextChangedListener(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) {
checkCancel();
int compare = count-before;
if(compare>1){
String text = editText.getText().toString();
String lastChar = (text.substring(text.length()-1,text.length()));
if(!lastChar.equals(" ")){
String plus = text+" ";
editText.setText(plus);
editText.setSelection(editText.getText().length());
}
}
}
#Override
public void afterTextChanged(Editable s) {
}
} );
You can see, onTextChanged can use the variables "before" and "count" and if the compare (difference between last word and current one) is more than 1, it's a word entered by Swipe. Then you can check if the "blankspace" is shown, and if not, just add it and perfom anything you want with it.
Hope it helps!
Could you try this? Add the filter into the editText. I used it for enter code on my app.
EditText et = (EditText) findViewById(R.id.edit_text);
et.setFilters(new InputFilter[] {
new InputFilter() {
#Override
public CharSequence filter(CharSequence charSequence, int start, int end, Spanned spanned, int start, int end {
if(charSequence.equals("")){
return charSequence;
}
if(charSequence.toString().matches("[a-zA-Z ]+")){
return charSequence;
}
return "";
}
}
});
So I uninstalled the google keyboard and reinstalled and I changed the build to release. One of those two things fixed it.

How to use EditText onClick method while remaining focused

I have an EditText that has a ListPopupWindow attached to it with recent search queries listed. When a user clicks the EditText, the popup should show, then when the user starts typing, the popup should disappear.
This is mostly working using OnFocusChangeListener, OnTextChangedListener, and OnEditorActionListener. However, if a user has clicked on the EditText, began to type, then clicks the EditText again, I need the popup to come back up. I have tried using an OnClickListener instead of an OnFocusChangeListener but can never get the popup to show with an OnClickListener.
How can I get the ListPopUpWindow to show when the use clicks the EditText if it already has focus?
searchBox.setOnFocusChangeListener(new View.OnFocusChangeListener() {
public void onFocusChange(View v, boolean gainFocus) {
//onFocus
if (gainFocus) {
popUpWindow.show();
}
}
});
To dismiss popup once user start typing in EditText field
searchBox.addTextChangedListener(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) {
}
#Override
public void afterTextChanged(Editable s) {
popUpWindow.dismiss();
}
});
To clear focus, dismiss popup, and execute search
searchBox.setOnEditorActionListener(new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if ((actionId & v.getImeOptions()) == actionId) {
if (event != null && event.getAction() == KeyEvent.ACTION_DOWN) {
if (searchBox.getText().toString().length() == 0) return true;
searchBox.clearFocus();
popUpWindow.dismiss();
fetchResults();
Util.hideKeyboard(v);
return true;
}
}
return false;
}
});
You can try replacing the focus change listener with an on touch listener and showing the popup when a MOTION_UP event occurs:
editText.setOnTouchListener(new OnTouchListener() {
#Override
public boolean onTouch(View v, MotionEvent event) {
if ((event.getAction() == MotionEvent.ACTION_UP) {
// Show popup here
}
return false;
}
});
I found the problem. It turns out I wasn't actually using an EditText object, but rather a custom class called MaterialEditText that provides a wrapper around an EditText object to give it Material UI features. The class passes the listeners I had been using onto it's EditText member, however, it was not doing so for either OnClickListener or OnTouchListener, so these listeners were never getting set for the EditText object. Once I added methods to pass these listeners on to the EditText object, I fixed my issue by keeping the code listed above and adding the following:
searchBox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// Show Popup
}
});

Making custom search suggestions in ActionBarSherlock search bar

This is how I do my basic search using the ActionBar Search widget. This is obviously the easy way where the suggestions are provided in a listView in the layout. But I want the suggestions inside the search box itself. Though it was possible to do it in a normal search box, how do I do the same using Actionbar Search box.
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
menu.add(0, 1, 1,"Search").setIcon(R.drawable.ic_search_inverse).setActionView(R.layout.collapsible_edittext).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case 1:
search = (AutoCompleteTextView) item.getActionView();
search.addTextChangedListener(filterTextWatcher);
search.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
return true;
}
return false;
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// your search logic here
doGeoSearch(String.valueOf(s));
}
};
public void doGeoSearch(String query){
Geocoder geocoder;
ArrayList<Address> addresses;
ArrayList<String> address = new ArrayList<String>() ;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = (ArrayList<Address>) geocoder.getFromLocationName(query, 6);
Log.d("Address",String.valueOf(addresses));
for(int i = 0;i<addresses.size();i++)
{
String addr = new String();
addr.concat(addresses.get(i).getAddressLine(0));
addr.concat(addresses.get(i).getAddressLine(1));
addr = addresses.get(i).getAddressLine(0) + addresses.get(i).getLocality() + addresses.get(i).getAdminArea();
//addr.concat(addresses.get(i).getAddressLine(2));
Log.d("addr",addr);
address.add(addr);
}
SearchAddressAdapater addressList = new SearchAddressAdapater(getApplicationContext(),R.layout.search_list,addresses, LocationActivity.this);
//addressView.setAdapter(addressList);
//ListView addressListView = new ListView();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can add a search widget to your ActionBar Sherlock, the search dialog has this functionality and it is very simple to implement as it is a simple expandable action item.
This tutorial will show you how to do everything you need with the search widget including search suggestions
Even though the SearchView was implemented and works, the search suggestions work on newer devices, but don't work on older devices like Gingerbread. Here's an issue:
https://github.com/JakeWharton/ActionBarSherlock/issues/659

Categories

Resources