I'm trying to use a SearchView and I got everything to work, except when I want to search an empty string.
The onQueryTextChange does react when I remove the last character, but I want the user to be able to press the search button when the searchfield is empty.
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
// Do something
return true;
}
#Override
public boolean onQueryTextSubmit(String query) {
// Do something
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
I've also tried using a OnKeyListner. but it does not seem to work either.
searchView.setOnKeyListener(new OnKeyListener() {
#Override
public boolean onKey(View arg0, int arg1, KeyEvent arg2) {
//Do something
return true;
}
});
This seems such a simple thing to do, but I can't get it to work. Any suggestions?
Edit
I have looked for a solution for a while now and just some minutes after posting this, I found a solution.
On this thread I found out this was not a bug, but it actually was deliberate.
Android SearchView.OnQueryTextListener OnQueryTextSubmit not fired on empty query string
So I just downloaded ActionBarSherlock and made some modification to the method onSubmitQuery()
From
private void onSubmitQuery() {
CharSequence query = mQueryTextView.getText();
if (query != null && TextUtils.getTrimmedLength(query) > 0) {
if (mOnQueryChangeListener == null
|| !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
if (mSearchable != null) {
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
setImeVisibility(false);
}
dismissSuggestions();
}
}
}
And the modified version
private void onSubmitQuery() {
CharSequence query = mQueryTextView.getText();
if(query == null) {query = "";}
if (mOnQueryChangeListener == null
|| !mOnQueryChangeListener.onQueryTextSubmit(query.toString())) {
if (mSearchable != null) {
launchQuerySearch(KeyEvent.KEYCODE_UNKNOWN, null, query.toString());
setImeVisibility(false);
}
dismissSuggestions();
}
}
Hope this helps if anyone else is having this problem.
Perhaps it's not suited for your app but you also have the option to use a simple EditText, then add a TextWatcher listener. This way you catch every input even if the user enters an empty string.
I had same issue with SearchView but I did not want to use ActionBarSherlock so I came up with solution which consists of styling your own SearchView as shown in guide http://novoda.com/blog/styling-the-actionbar-searchview/ and setting OnEditorActionListener for EditText( How do I trigger an action when the user has hit enter?) which is part of the SearchView.
final SearchView searchView = (SearchView)findViewById(R.id.search);
int searchPlateId = searchView.getContext().getResources().getIdentifier("android:id/search_src_text", null, null);
EditText searchPlate = (EditText) searchView.findViewById(searchPlateId);
searchPlate.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
//Do something
}
return false;
});
Related
I am trying to have it so that when I hit enter the recyclerview is cleared out of the old data and new data is grabbed and put in and displayed. I have it so that anytime that enter is hit it grabs what is in the edittext and put that into a variable that is then searched for. The variable is being updated but the array that holds the searched for items isn't updated. Do I need to clear that array out? I think to do that I would need to use an ArrayList instead of a normal array. Would that be a better idea?
public View.OnKeyListener search = new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
searchItem = "";
if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
{
if(searchItem != searchBar.getText().toString())
{
searchItem = searchBar.getText().toString();
Toast.makeText(imdb_activity.this, "The search is: " + searchItem, Toast.LENGTH_SHORT).show();
Log.d("Android view component", "Enter button was pressed and the value is: " + searchItem);
}
//clear recyclerview?
goGetSearch();
return true;
}
return false;
}
};
you need to pass the updated list to the recyclerview, I assume that goGetSearch is the function where you pass the parameters to recyclerview and the searchItem is your list, so I hope you got the concept and if my assumption is wrong, you can edit it to fit in your case.
public View.OnKeyListener search = new View.OnKeyListener()
{
#Override
public boolean onKey(View v, int keyCode, KeyEvent event)
{
searchItem = "";
if(event.getAction() == KeyEvent.ACTION_DOWN && keyCode == KeyEvent.KEYCODE_ENTER)
{
if(searchItem != searchBar.getText().toString())
{
searchItem = searchBar.getText().toString();
Toast.makeText(imdb_activity.this, "The search is: " + searchItem,
Toast.LENGTH_SHORT).show();
Log.d("Android view component", "Enter button was pressed and the value
is: " + searchItem);
}
//clear recyclerview?
goGetSearch(searchItem);
return true;
}
return false;
}
};
I have a multiline editText in my activity. And what I want is ecerytime the user inputs new line / next line / enter , a bullet should be generated automatically. What should I do? Below is an example of the expected output:
• Item 1 (user presses enter / new line)
•
What I'm not sure about is if you also want the first line to get a bullet automatically. Try this for getting a bullet in the new line:
final EditText et = findViewById(R.id.edittext);
et.setOnKeyListener(new View.OnKeyListener() {
#Override
public boolean onKey(View view, int i, KeyEvent event) {
// onKey is fired twice, we filter one out
if (event.getAction()!=KeyEvent.ACTION_UP) {
return false;
}
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
String oldString = et.getText().toString();
String newString = oldString + "\u25CF";
et.setText(newString);
et.setSelection(et.getText().length());
}
return false;
}
});
You can add a character to do this.
• = \u2022
● = \u25CF
You should be able to add one to the editbox.
yourBox.setOnKeyListener(new View.OnKeyListener() {
#Override public boolean onKey (View v,int keyCode, KeyEvent event){
if (event.getKeyCode() == KeyEvent.KEYCODE_ENTER) {
String myString = yourBox.getText().toString();
yourBox.setText("\u25CF " + myString);
}
return false;
}
});
I need drag and drop in my new project. I referred this blogpost. But I'm facing a problem while performing Drop. I cannot get the image which I hold and can't drop into view. DragListner which I used is given below. I don't know how to handle the dropevent.
class MyDragListener implements OnDragListener {
#Override
public boolean onDrag(View view, DragEvent dragEvent) {
int dragAction = dragEvent.getAction();
View dragView = (View) dragEvent.getLocalState();
if (dragAction == DragEvent.ACTION_DRAG_EXITED) {
System.out.println("exit------------");
containsDragable = false;
} else if (dragAction == DragEvent.ACTION_DRAG_ENTERED) {
System.out.println("enter------------");
containsDragable = true;
} else if (dragAction == DragEvent.ACTION_DRAG_ENDED) {
System.out.println("end------------");
dragView.setVisibility(View.VISIBLE);
} else if (dragAction == DragEvent.ACTION_DROP && containsDragable) {
dragView.setVisibility(View.VISIBLE);
}
return true;
}
maybe at first you can print out the
DragEvent.ACTION_DROP
code, and compare it to the value of the dragAction .
if the value is the same then the problem are at containsDragable function.
hope this helps
I've been racking my brains all night but can't seem to accomplish this one small thing. I would like to add a SwitchPreference into my PreferenceActivity of an app. Below is a picture.
Before I say too much, my problem is exactly this: I cannot seem to put a listener on just the Switch part of the preference. I am able to set an onPreferenceTreeClick and an onPreferenceClick on the preference, and that works fine if I press on the text portion. But When the Switch itself does nothing when I change it from OFF to ON.
I've read the documentation on SwitchPreference. I also looked at the android/packages/Settings and it looks like AOSP uses a Switch and not a SwitchPreference for Wi-Fi and Bluetooth.
Here is my attempt (working if you press on the entire preference item, but not if you just press the Switch):
Sample:
public class Preferences extends SherlockPreferenceActivity {
public static final String PREF_THEME = "pref_theme_interface";
public static final String PREF_ROOT = "pref_root";
public static final String PREF_APP = "pref_app";
public static SharedPreferences mTheme;
private static SharedPreferences mUpdate;
public static SharedPreferences.Editor mEditor;
public boolean SDK_COMPAT = true;
boolean pSwitch = false;
boolean update = true;
Preference autoUpdate;
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
this.finish();
break;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onCreate(Bundle savedInstanceState) {
setTheme(MainActivity.THEME);
super.onCreate(savedInstanceState);
final ActionBar actionBar = getSupportActionBar();
actionBar.setHomeButtonEnabled(true);
actionBar.setDisplayHomeAsUpEnabled(true);
actionBar.setIcon(R.drawable.ic_preferences);
if (Build.VERSION.SDK_INT < Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
SDK_COMPAT = false;
}
mUpdate = PreferenceManager.getDefaultSharedPreferences(this);
update = mUpdate.getBoolean("update", false);
// Load the preferences from an XML resource
addPreferencesFromResource(R.xml.preferences);
setPreferenceScreen(createPreferenceSDK());
}
private PreferenceScreen createPreferenceSDK() {
// Root
PreferenceScreen root = (PreferenceScreen)findPreference(PREF_ROOT);
PreferenceCategory prefApp = (PreferenceCategory)findPreference(PREF_APP);
//root.addPreference(prefApp);
if (SDK_COMPAT == true) {
pSwitch = true;
autoUpdate = new SwitchPreference(this);
autoUpdate.setKey("auto_update_pref");
autoUpdate.setTitle(R.string.auto_update);
//autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
prefApp.addPreference(autoUpdate);
} else {
pSwitch = false;
autoUpdate = new CheckBoxPreference(this);
autoUpdate.setKey("auto_update_pref");
autoUpdate.setTitle(R.string.auto_update);
autoUpdate.setSummary(R.string.auto_update_summary);
prefApp.addPreference(autoUpdate);
}
autoUpdate.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
mEditor = mUpdate.edit();
boolean checked = ((SwitchPreference) preference)
.isChecked();
if (checked) {
update = true;
mEditor.putBoolean("update", true);
mEditor.commit();
autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
} else {
update = false;
mEditor.putBoolean("update", false);
mEditor.commit();
autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
}
return true;
}
});
return root;
}
So to reiterate my question in case I lost you. How does one set a listener on the Switch portion of the SwitchPreference? Please be kind if it is something so obvious. It was pretty late last night when I tried to add this.
Thank you so much in advance.
Notes:
1. I am not opposed to sticking with the CheckBoxPreference, but I prefer to use Switch because it looks nice.
Yes I know there is an easier/better? way of adding dynamic preference using res/xml and res/xml-v14 instead of doing the SDK check. I just did that for testing.
picture of preference screen
EDIT
Hopefully this helps someone else! Thanks Tushar for suggestion :-)
autoUpdate.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference,
Object newValue) {
boolean switched = ((SwitchPreference) preference)
.isChecked();
update = !switched;
mEditor = mUpdate.edit();
mEditor.putBoolean("update", update);
mEditor.commit();
autoUpdate.setSummary(update == false ? "Disabled" : "Enabled");
return true;
}
});
Use setOnPreferenceChangeListener() instead of setOnPreferenceClickListener().
Working code
public static class SettingsFragment extends PreferenceFragment {
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
addPreferencesFromResource(R.xml.pref_notification);
SwitchPreference vibrateSwitch = (SwitchPreference) findPreference("notification_vibrate");
if (vibrateSwitch != null) {
vibrateSwitch.setOnPreferenceChangeListener(new Preference.OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference arg0, Object isVibrateOnObject) {
boolean isVibrateOn = (Boolean) isVibrateOnObject;
if (isVibrateOn) {
Vibrator v = (Vibrator) getActivity().getSystemService(Context.VIBRATOR_SERVICE);
v.vibrate(400);
}
return true;
}
});
}
}
}
If you still haven't figured out a good way for doing this I have figured something out that doesn't create multiple calls to onPreferenceChange which clicking the preference does. I wrote it in another question: dual functionality SwitchPreference.
I've searched long and far and found a few different ways people are dealing with removing a single and often specific tab from a TabHost object. I would like to try, if I may, to gather all those methods to this single question so that people my "shop" for the right method they need and hopefully get the answer they need to write their code; I also feel that it will cut down on the number of these questions.
At the moment I'm having trouble finding a solution to my code as well. I'm attempting to get rid of a particular tab without touching the others; hopefully I too will find my answer.
I wont pick a particular answer for this question for a while, so please just list the method you used to deal with this problem here for others to see.
Thank you.
Update:
Okay, here is my current code:
TabHost mTabHost;
TabHost.TabSpec spec;
Intent mSettingsIntent;
Intent mSearchIntent;
int tabNum = 1;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mSearchIntent = new Intent().setClass(this, SearchTab.class);
mTabHost = getTabHost();
mTabHost.getTabWidget().setDividerDrawable(R.drawable.tab_divider);
makeTab("Tab");
final Button newSearchBtn = (Button) findViewById(R.id.new_search_btn);
newSearchBtn.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
// Perform action on clicks
EditText searchBar = (EditText) findViewById(R.id.search_bar);
final String searchString = searchBar.getText().toString();
makeTab(searchString);
}
});
final EditText edittext = (EditText) findViewById(R.id.search_bar);
edittext.setOnKeyListener(new OnKeyListener() {
public boolean onKey(View v, int keyCode, KeyEvent event) {
// If the event is a key-down event on the "enter" button
if ((event.getAction() == KeyEvent.ACTION_DOWN) &&
(keyCode == KeyEvent.KEYCODE_ENTER)) {
// Perform action on key press
EditText searchBar = (EditText) findViewById(R.id.search_bar);
final String searchString = searchBar.getText().toString();
makeTab(searchString);
return true;
}
return false;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.tab_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.menu_close:
// TODO: Find/define method to close a single tab
closeTab();
return true;
case R.id.menu_settings:
// TODO: Create a basic Settings Activity and call constructor here
return true;
default:
return super.onOptionsItemSelected(item);
}
}
public void makeTab(String tabText) {
String tabTag = "Tab" + tabNum++;
View tabview = createTabView(mTabHost.getContext(), tabText);
spec = mTabHost.newTabSpec(tabTag).setIndicator(tabview).setContent(new Intent().setClass(this, SearchTab.class));
mTabHost.addTab(spec);
mTabHost.setCurrentTabByTag(tabTag);
}
private void closeTab() {
// TODO: Define method for closing a single tab with tabTag
mTabHost.removeViewAt(mTabHost.getCurrentTab());
}
private static View createTabView(final Context context, final String text) {
View view = LayoutInflater.from(context).inflate(R.layout.tabs_bg, null);
TextView tv = (TextView) view.findViewById(R.id.tabsText);
tv.setText(text);
return view;
}
}
My app locks up due to a NullPointer Exception I'm not sure why; I'm still trying to figure out how to read the debugger perspective in Eclispe for clues. I'll update when I have more.