I am creating a custom Android ActionBar search following this tutorial.
The handleMenuSearch(); is activated on onOptionsItemSelected.
protected void handleMenuSearch(){
ActionBar action = getSupportActionBar(); //get the actionbar
if(isSearchOpened){ //test if the search is open
action.setDisplayShowCustomEnabled(false); //disable a custom view inside the actionbar
action.setDisplayShowTitleEnabled(true); //show the title in the action bar
//hides the keyboard
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(edtSeach.getWindowToken(), 0);
//add the search icon in the action bar
mSearchAction.setIcon(getResources().getDrawable(R.drawable.search));
isSearchOpened = false;
} else { //open the search entry
action.setDisplayShowCustomEnabled(true); //enable it to display a
// custom view in the action bar.
action.setCustomView(R.layout.search_bar);//add the custom view
action.setDisplayShowTitleEnabled(false); //hide the title
edtSeach = (EditText)action.getCustomView().findViewById(R.id.edtSearch); //the text editor
edtSeach.requestFocus();
edtSeach.addTextChangedListener(new TextWatcher() {
public void onTextChanged(CharSequence s, int start, int before, int count) {
loadData(edtSeach.getText().toString());
}
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
}
public void afterTextChanged(Editable s) {
}
});
//open the keyboard focused in the edtSearch
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.showSoftInput(edtSeach, InputMethodManager.SHOW_IMPLICIT);
//add the close icon
mSearchAction.setIcon(getResources().getDrawable(R.drawable.ximage));
isSearchOpened = true;
}
}
What I want to achieve is to activate the searching once the activity is started.
I tried to put handleMenuSearch(); under onCreate but this gives me NullPointerException
The reason for this I guess is because I cannot call mSearchAction from onCreate.
public boolean onPrepareOptionsMenu(Menu menu) {
mSearchAction = menu.findItem(R.id.search);
return super.onPrepareOptionsMenu(menu);
}
Problem solved by using Handler.
protected void onResume() {
super.onResume();
new Handler().postDelayed(new Runnable() {
public void run() {
handleMenuSearch();
}
}, 1000);
}
Related
I ran into some strange UI issues while trying to display a custom content AlertDialog. The dialog asks the user to enter a name and it doesn't allow him to move forward without doing so. It is also the first thing that the user sees when the activity starts.
Sometimes, right after the application gets restarted - let's say I press the home button when the dialog is opened and then I reopen the app, the AlertDialog is being displayed as it should be but the parent activity's layout is not being loaded correctly. It actually keeps the layout from the previous Activity that the user was seeing. Even stranger, this layout is almost always displayed backwards. You can probably see that better in here. Behind the dialog it should be a blank white layout but instead there's a reverted "snapshot" of the launcher activity from the Settings app.
As the official documentation suggests I am wrapping the AlertDialog in a DialogFragment.
public class NicknamePickerDialog extends DialogFragment {
public static final String TAG = NicknamePickerDialog.class.getSimpleName();
public interface NicknameDialogListener {
void onNicknamePicked(String nickname);
void onPickerCanceled();
}
private NicknameDialogListener mListener;
private EditText mNicknameEditText;
private Button mPositiveButton;
public void setNicknameDialogListener(NicknameDialogListener listener) {
mListener = listener;
}
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
// Set the title
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setTitle(R.string.pick_nickname);
// Inflate the custom content
View dialogView = getActivity().getLayoutInflater().inflate(R.layout.nickname_dialog_layout, null);
builder.setView(dialogView);
mNicknameEditText = (EditText) dialogView.findViewById(R.id.nickname);
builder.setPositiveButton(R.string.great, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mListener != null) {
mListener.onNicknamePicked(mNicknameEditText.getText().toString());
}
}
});
builder.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if (mListener != null) {
mListener.onPickerCanceled();
}
}
});
final AlertDialog dialog = builder.create();
dialog.setOnShowListener(new DialogInterface.OnShowListener() {
#Override
public void onShow(DialogInterface dialogInterface) {
mPositiveButton = dialog.getButton(Dialog.BUTTON_POSITIVE);
mPositiveButton.setEnabled(false);
}
});
mNicknameEditText.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) {
mPositiveButton.setEnabled(s.length() != 0);
}
});
return dialog;
}
}
This is the Activity code
public class ChatActivity extends Activity implements NicknamePickerDialog.NicknameDialogListener {
private String mNickname;
private TextView mWelcomeTextView;
private NicknamePickerDialog mDialog;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.chat_activity_layout);
mWelcomeTextView = (TextView) findViewById(R.id.welcome);
mDialog = new NicknamePickerDialog();
mDialog.setNicknameDialogListener(this);
}
private void showNicknamePickerDialog() {
mDialog.show(getFragmentManager(), NicknamePickerDialog.TAG);
}
#Override
public void onNicknamePicked(String nickname) {
mNickname = nickname;
mWelcomeTextView.setText("Welcome " + nickname + "!");
}
#Override
public void onPickerCanceled() {
if (mNickname == null) {
finish();
}
}
#Override
protected void onResume() {
super.onResume();
if (mNickname == null) {
showNicknamePickerDialog();
};
}
#Override
protected void onPause() {
super.onPause();
mDialog.dismiss();
}
}
At first I suspected that it probably happens because I am calling the DialogFragment's show method inside the activity's onCreate() callback (as it might be too soon), but postponing it to as late as onResume() does not solve the problem. This issue also occurs on orientation changes, leaving the background behind the dialog black. I am sure I am doing something wrong but I really can't find out what that is.
I am seriously not getting that what you are trying to do. but one thing you have done the wrong is that.
Do overide method OnCreateView() in class NicknamePickerDialog and do the below
// Inflate the custom content
View dialogView = getActivity().getLayoutInflater().inflate(R.layout.nickname_dialog_layout, null);
builder.setView(dialogView);
mNicknameEditText = (EditText) dialogView.findViewById(R.id.nickname);
mNicknameEditText.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) {
mPositiveButton.setEnabled(s.length() != 0);
}
});
return dialogView;
also your alert dialog will not work . better create buttons and title you can in onCreateDialog().
dialog.setTitle(R.string.pick_nickname);
Hope this will work.
WhatsApp has such Toolbar:
When 'Search' menu item clicked, from the top SearchView comes down which takes whole space of toolbar:
When I tried to implement SearchView, it looks like this:
I found some libraries to implement this:
Android Material SearchView by Eugene Horan
and MaterialSearchView by krishnakapil. But they are not like in WhatsApp.
This question may seem weird, I could not find the way how to do this. So my question is how to implement WhatsApp like material design SearchView which comes from the top?
I have developed a well received library by the comunity.
Does exactly what are you looking for.
Give it a try and tell if if was usufull for you.
Here it is the Github repo for MaterialSearchView.
You can create this with android.support.v7 library
First of all create menu item in menu.xml like:
<item android:id="#+id/action_search"
android:title="Search"
android:icon="#drawable/abc_ic_search_api_mtrl_alpha"
app:showAsAction="ifRoom|collapseActionView"
app:actionViewClass="android.support.v7.widget.SearchView" />
Extend AppCompatActivity and retrieve the SearchView in onCreateOptionsMenu like:
import android.support.v7.widget.SearchView;
...
public class YourActivity extends AppCompatActivity {
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_home, menu);
// Retrieve the SearchView and plug it into SearchManager
final SearchView searchView = (SearchView) MenuItemCompat.getActionView(menu.findItem(R.id.action_search));
SearchManager searchManager = (SearchManager) getSystemService(SEARCH_SERVICE);
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
return true;
}
...
}
Thats it. Hope this helps you. Accept, if you find it useful.
Sorry, I misread the question.
This answer should solve your issue.
Answer taken from :- Creating a SearchView that looks like the material design guidelines
After a week of puzzling over this. I think I've figured it out.
I'm now using just an EditText inside of the Toolbar. This was suggested to me by oj88 on reddit.
I now have this:
First inside onCreate() of my activity I added the EditText with an image view on the right hand side to the Toolbar like this:
// Setup search container view
searchContainer = new LinearLayout(this);
Toolbar.LayoutParams containerParams = new Toolbar.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT);
containerParams.gravity = Gravity.CENTER_VERTICAL;
searchContainer.setLayoutParams(containerParams);
// Setup search view
toolbarSearchView = new EditText(this);
// Set width / height / gravity
int[] textSizeAttr = new int[]{android.R.attr.actionBarSize};
int indexOfAttrTextSize = 0;
TypedArray a = obtainStyledAttributes(new TypedValue().data, textSizeAttr);
int actionBarHeight = a.getDimensionPixelSize(indexOfAttrTextSize, -1);
a.recycle();
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(0, actionBarHeight);
params.gravity = Gravity.CENTER_VERTICAL;
params.weight = 1;
toolbarSearchView.setLayoutParams(params);
// Setup display
toolbarSearchView.setBackgroundColor(Color.TRANSPARENT);
toolbarSearchView.setPadding(2, 0, 0, 0);
toolbarSearchView.setTextColor(Color.WHITE);
toolbarSearchView.setGravity(Gravity.CENTER_VERTICAL);
toolbarSearchView.setSingleLine(true);
toolbarSearchView.setImeActionLabel("Search", EditorInfo.IME_ACTION_UNSPECIFIED);
toolbarSearchView.setHint("Search");
toolbarSearchView.setHintTextColor(Color.parseColor("#b3ffffff"));
try {
// Set cursor colour to white
// https://stackoverflow.com/a/26544231/1692770
// https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(toolbarSearchView, R.drawable.edittext_whitecursor);
} catch (Exception ignored) {
}
// Search text changed listener
toolbarSearchView.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) {
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.container);
if (mainFragment != null && mainFragment instanceof MainListFragment) {
((MainListFragment) mainFragment).search(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
// https://stackoverflow.com/a/6438918/1692770
if (s.toString().length() <= 0) {
toolbarSearchView.setHintTextColor(Color.parseColor("#b3ffffff"));
}
}
});
((LinearLayout) searchContainer).addView(toolbarSearchView);
// Setup the clear button
searchClearButton = new ImageView(this);
Resources r = getResources();
int px = (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, 16, r.getDisplayMetrics());
LinearLayout.LayoutParams clearParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
clearParams.gravity = Gravity.CENTER;
searchClearButton.setLayoutParams(clearParams);
searchClearButton.setImageResource(R.drawable.ic_close_white_24dp); // TODO: Get this image from here: https://github.com/google/material-design-icons
searchClearButton.setPadding(px, 0, px, 0);
searchClearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toolbarSearchView.setText("");
}
});
((LinearLayout) searchContainer).addView(searchClearButton);
// Add search view to toolbar and hide it
searchContainer.setVisibility(View.GONE);
toolbar.addView(searchContainer);
This worked, but then I came across an issue where onOptionsItemSelected() wasn't being called when I tapped on the home button. So I wasn't able to cancel the search by pressing the home button. I tried a few different ways of registering the click listener on the home button but they didn't work. Eventually I found out that the ActionBarDrawerToggle I had was interfering with things, so I removed it. This listener then started working:
toolbar.setNavigationOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// toolbarHomeButtonAnimating is a boolean that is initialized as false. It's used to stop the user pressing the home button while it is animating and breaking things.
if (!toolbarHomeButtonAnimating) {
// Here you'll want to check if you have a search query set, if you don't then hide the search box.
// My main fragment handles this stuff, so I call its methods.
FragmentManager fragmentManager = getFragmentManager();
final Fragment fragment = fragmentManager.findFragmentById(R.id.container);
if (fragment != null && fragment instanceof MainListFragment) {
if (((MainListFragment) fragment).hasSearchQuery() || searchContainer.getVisibility() == View.VISIBLE) {
displaySearchView(false);
return;
}
}
}
if (mDrawerLayout.isDrawerOpen(findViewById(R.id.navigation_drawer)))
mDrawerLayout.closeDrawer(findViewById(R.id.navigation_drawer));
else
mDrawerLayout.openDrawer(findViewById(R.id.navigation_drawer));
}
});
So I can now cancel the search with the home button, but I can't press the back button to cancel it yet. So I added this to onBackPressed():
FragmentManager fragmentManager = getFragmentManager();
final Fragment mainFragment = fragmentManager.findFragmentById(R.id.container);
if (mainFragment != null && mainFragment instanceof MainListFragment) {
if (((MainListFragment) mainFragment).hasSearchQuery() || searchContainer.getVisibility() == View.VISIBLE) {
displaySearchView(false);
return;
}
}
I created this method to toggle visibility of the EditText and menu item:
public void displaySearchView(boolean visible) {
if (visible) {
// Stops user from being able to open drawer while searching
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_LOCKED_CLOSED);
// Hide search button, display EditText
menu.findItem(R.id.action_search).setVisible(false);
searchContainer.setVisibility(View.VISIBLE);
// Animate the home icon to the back arrow
toggleActionBarIcon(ActionDrawableState.ARROW, mDrawerToggle, true);
// Shift focus to the search EditText
toolbarSearchView.requestFocus();
// Pop up the soft keyboard
new Handler().postDelayed(new Runnable() {
public void run() {
toolbarSearchView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_DOWN, 0, 0, 0));
toolbarSearchView.dispatchTouchEvent(MotionEvent.obtain(SystemClock.uptimeMillis(), SystemClock.uptimeMillis(), MotionEvent.ACTION_UP, 0, 0, 0));
}
}, 200);
} else {
// Allows user to open drawer again
mDrawerLayout.setDrawerLockMode(DrawerLayout.LOCK_MODE_UNLOCKED);
// Hide the EditText and put the search button back on the Toolbar.
// This sometimes fails when it isn't postDelayed(), don't know why.
toolbarSearchView.postDelayed(new Runnable() {
#Override
public void run() {
toolbarSearchView.setText("");
searchContainer.setVisibility(View.GONE);
menu.findItem(R.id.action_search).setVisible(true);
}
}, 200);
// Turn the home button back into a drawer icon
toggleActionBarIcon(ActionDrawableState.BURGER, mDrawerToggle, true);
// Hide the keyboard because the search box has been hidden
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(toolbarSearchView.getWindowToken(), 0);
}
}
I needed a way to toggle the home button on the toolbar between the drawer icon and the back button. I eventually found the method below in this SO answer. Though I modified it slightly to made more sense to me:
private enum ActionDrawableState {
BURGER, ARROW
}
/**
* Modified version of this, https://stackoverflow.com/a/26836272/1692770<br>
* I flipped the start offset around for the animations because it seemed like it was the wrong way around to me.<br>
* I also added a listener to the animation so I can find out when the home button has finished rotating.
*/
private void toggleActionBarIcon(final ActionDrawableState state, final ActionBarDrawerToggle toggle, boolean animate) {
if (animate) {
float start = state == ActionDrawableState.BURGER ? 1.0f : 0f;
float end = Math.abs(start - 1);
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
ValueAnimator offsetAnimator = ValueAnimator.ofFloat(start, end);
offsetAnimator.setDuration(300);
offsetAnimator.setInterpolator(new AccelerateDecelerateInterpolator());
offsetAnimator.addUpdateListener(new ValueAnimator.AnimatorUpdateListener() {
#Override
public void onAnimationUpdate(ValueAnimator animation) {
float offset = (Float) animation.getAnimatedValue();
toggle.onDrawerSlide(null, offset);
}
});
offsetAnimator.addListener(new Animator.AnimatorListener() {
#Override
public void onAnimationStart(Animator animation) {
}
#Override
public void onAnimationEnd(Animator animation) {
toolbarHomeButtonAnimating = false;
}
#Override
public void onAnimationCancel(Animator animation) {
}
#Override
public void onAnimationRepeat(Animator animation) {
}
});
toolbarHomeButtonAnimating = true;
offsetAnimator.start();
}
} else {
if (state == ActionDrawableState.BURGER) {
toggle.onDrawerClosed(null);
} else {
toggle.onDrawerOpened(null);
}
}
}
This works, I've managed to work out a few bugs that I found along the way. I don't think it's 100% but it works well enough for me.
EDIT: If you want to add the search view in XML instead of Java do this:
toolbar.xml:
<android.support.v7.widget.Toolbar
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:id="#+id/toolbar"
contentInsetLeft="72dp"
contentInsetStart="72dp"
android:layout_width="match_parent"
android:layout_height="?attr/actionBarSize"
android:background="?attr/colorPrimary"
android:elevation="4dp"
android:minHeight="?attr/actionBarSize"
app:contentInsetLeft="72dp"
app:contentInsetStart="72dp"
app:popupTheme="#style/ActionBarPopupThemeOverlay"
app:theme="#style/ActionBarThemeOverlay">
<LinearLayout
android:id="#+id/search_container"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_vertical"
android:orientation="horizontal">
<EditText
android:id="#+id/search_view"
android:layout_width="0dp"
android:layout_height="?attr/actionBarSize"
android:layout_weight="1"
android:background="#android:color/transparent"
android:gravity="center_vertical"
android:hint="Search"
android:imeOptions="actionSearch"
android:inputType="text"
android:maxLines="1"
android:paddingLeft="2dp"
android:singleLine="true"
android:textColor="#ffffff"
android:textColorHint="#b3ffffff" />
<ImageView
android:id="#+id/search_clear"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:paddingLeft="16dp"
android:paddingRight="16dp"
android:src="#drawable/ic_close_white_24dp" />
</LinearLayout>
</android.support.v7.widget.Toolbar>
onCreate() of your Activity:
searchContainer = findViewById(R.id.search_container);
toolbarSearchView = (EditText) findViewById(R.id.search_view);
searchClearButton = (ImageView) findViewById(R.id.search_clear);
// Setup search container view
try {
// Set cursor colour to white
// https://stackoverflow.com/a/26544231/1692770
// https://github.com/android/platform_frameworks_base/blob/kitkat-release/core/java/android/widget/TextView.java#L562-564
Field f = TextView.class.getDeclaredField("mCursorDrawableRes");
f.setAccessible(true);
f.set(toolbarSearchView, R.drawable.edittext_whitecursor);
} catch (Exception ignored) {
}
// Search text changed listener
toolbarSearchView.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) {
Fragment mainFragment = getFragmentManager().findFragmentById(R.id.container);
if (mainFragment != null && mainFragment instanceof MainListFragment) {
((MainListFragment) mainFragment).search(s.toString());
}
}
#Override
public void afterTextChanged(Editable s) {
}
});
// Clear search text when clear button is tapped
searchClearButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
toolbarSearchView.setText("");
}
});
// Hide the search view
searchContainer.setVisibility(View.GONE);
I've just post my open source which imitates exactly what whatsapp toolbar does (Include circular animation).
Code
Full example
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)
I have an application in which I scan for input using a bluetooth scanner. When my current intent receives an input, I setResult and finish the activity, and then another intent is started. However, when my activity receives input and closes and after that when a new activity is started, instead of allowing me to scan a new input, it takes the old input and moves on. How do I stop this. This is what I am doing inside onCreate():
barcodeEntry = (EditText) findViewById(R.id.barcode_input);
barcodeEntry.requestFocus();
barcodeEntry.addTextChangedListener(new TextWatcher() {
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
#Override
public void afterTextChanged(Editable s) {
Toast toast = Toast.makeText(getApplicationContext(),
"Received Scan", Toast.LENGTH_SHORT);
toast.show();
Intent returnIntent = new Intent();
returnIntent.putExtra(WorkflowUtil.EXTRA_ACTION, barcodeEntry.getText().toString());
setResult(RESULT_OK, returnIntent);
finish();
}
});
This is what my EditText decalaration in layout look like:
<EditText
android:id="#+id/barcode_input"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="left"
android:layout_marginTop="10dp"
android:background="#000000"
android:enabled="true"
android:inputType="text"
android:textColor="#000000"
android:textSize="20sp"
android:visibility="visible" />
How do I stop this. Will it work if I stop a View from receving focus when it is loaded?
here's how to hide the softkeyboard of the view:
/** hides the soft keyboard for a specific view */
public static void hideSoftKeyboardFromFocusedView(final Context context, final View view)
{
final InputMethodManager imm = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
}
a similar thing can be done to show the softkeyboard.
here's how to force focus on a EditText, and by this, also show the softkeyboard, even if the view already has focus:
public static void forceFocusOnView(final View view)
{
view.post(new Runnable()
{
#Override
public void run()
{
view.clearFocus();
view.post(new Runnable()
{
#Override
public void run()
{
view.requestFocus();
}
});
}
});
}
if that doesn't work, you can use:
public static void focusAndShowSoftKeyboardOnView(final View v)
{
new Handler().post(new Runnable()
{
#Override
public void run()
{
v.requestFocus();
}
});
final InputMethodManager m = (InputMethodManager)v.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
if (m != null)
m.toggleSoftInput(0, InputMethodManager.SHOW_IMPLICIT);
}
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