I have been trying to redirect my searchview results to another activity upon onquerysubmit but the app just shows me a blank page. I have been trying to debug it but after the onquerysubmit returns false, the debugger just keeps on displaying that the app is running.
Here is my AndroidManifest.xml
<activity
android:name=".UniversalSearchActivity"
android:label="#string/title_activity_universal_search"
android:theme="#style/AppTheme"
android:launchMode="singleTop">
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
<activity
android:name=".UniversalSearchResultActivity"
android:label="#string/title_activity_report_error"
android:parentActivityName=".UniversalSearchActivity"
android:theme="#style/AppTheme">
</activity>
UniversalSearchActivity.java
public class UniversalSearchActivity extends AppCompatActivity {
private RelativeLayout searchSuggestionsLayout;
private ListView searchListView;
private SearchView searchView;
private UniversalSearchAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_universal_search);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar_universal_search);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
searchSuggestionsLayout = (RelativeLayout) findViewById(R.id.search_suggestions_container);
searchListView = (ListView) findViewById(R.id.search_suggestions_list);
adapter = new UniversalSearchAdapter(this, this.getSearch());
searchListView.setAdapter(adapter);
searchListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Toast.makeText(getApplicationContext(), "You clicked an item in the list view!",
Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_main, menu);
MenuItem searchItem = menu.findItem(R.id.search);
searchItem.expandActionView();
SearchManager searchManager =
(SearchManager) this.getSystemService(Context.SEARCH_SERVICE);
searchView = new SearchView(getSupportActionBar().getThemedContext());
searchView.setSearchableInfo(
searchManager.getSearchableInfo(new ComponentName(this,
UniversalSearchResultActivity.class)));
searchView.setQueryHint(getString(R.string.placeholder_universal_search));
searchView.setSubmitButtonEnabled(true);
searchView.setIconified(false);
searchView.requestFocus();
menu.add("Search")
.setIcon(R.drawable.ic_search)
.setActionView(searchView)
.setShowAsAction(MenuItem.SHOW_AS_ACTION_ALWAYS);
final SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextChange(String newText) {
adapter.getFilter().filter(newText);
return false;
}
#Override
public boolean onQueryTextSubmit(String query) {
if(query == "") {
Toast.makeText(getApplicationContext(), "Please type a hint", Toast.LENGTH_SHORT)
.show();
} else {
Intent intent = new Intent(getApplicationContext(),
UniversalSearchResultActivity.class);
startActivity(intent);
}
return false;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
public ArrayList<UniversalSearch> getSearch() {
ArrayList<UniversalSearch> searches = new ArrayList<UniversalSearch>();
UniversalSearch universalSearch;
for (int i=0; i<names.length; i++) {
universalSearch = new UniversalSearch(names[i], address[i], images[i]);
searches.add(universalSearch);
}
return searches;
}
}
UniversalSearchResultActivity.java
public class UniversalSearchResultActivity extends AppCompatActivity {
private RelativeLayout searchResultLayout;
private ListView searchResultListView;
private UniversalSearchAdapter universalSearchAdapter;
#Override
public void onCreate(Bundle savedInstanceState, PersistableBundle persistentState) {
super.onCreate(savedInstanceState, persistentState);
setContentView(R.layout.activity_universal_search_result);
Toolbar toolbar = (Toolbar) findViewById(R.id.tool_bar_universal_search_result);
setSupportActionBar(toolbar);
getSupportActionBar().setTitle("");
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
Toast.makeText(getApplicationContext(), "I'm heeeere!!!", Toast.LENGTH_SHORT).show();
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
setIntent(intent);
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
Intent resultIntent = new Intent(getApplicationContext(),
UniversalSearchResultActivity.class);
resultIntent.putExtra(SearchManager.QUERY, query);
}
}
}
The searchview works fine when the onquerytextchange is used but in the case of onquerytextsubmit, it doesn't. Please tell me what I am doing wrong. Thank you!
Related
I am a begineer in Android programming. I am getting trouble with this problem from 3 days. Any suggestion plz.
MainActivity.java
public class MainActivity extends AppCompatActivity implements SearchView.OnQueryTextListener,
View.OnLongClickListener, BeneficiaryRecyclerAdapter.ListItemClickListener {
private AppCompatActivity activity = MainActivity.this;
public boolean is_in_action_mode = false;
private RecyclerView recyclerViewBeneficiary;
private Beneficiary beneficiary;
private ArrayList<Beneficiary> listBeneficiary;
ArrayList<Beneficiary> selection_list = new ArrayList<>();
private BeneficiaryRecyclerAdapter beneficiaryRecyclerAdapter;
private DatabaseHelper databaseHelper;
Toolbar toolbar;
TextView counter_text_view;
int counter = 0, id;
private SQLiteDatabase mDb;
private final static String TAG = "check";
#Override
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
//toolbar.inflateMenu(R.menu.menu_activity_main);
counter_text_view = (TextView) findViewById(R.id.counter_text);
counter_text_view.setText(getString(R.string.app_name));
recyclerViewBeneficiary = (RecyclerView) findViewById(R.id.listRecyclerView);
initObjects();
FloatingActionButton fab = (FloatingActionButton) findViewById(R.id.addAccountFab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(MainActivity.this,
AccountDetailActivity.class);
startActivity(intent);
}
});
}
private void initObjects() {
listBeneficiary = new ArrayList<>();
beneficiaryRecyclerAdapter = new BeneficiaryRecyclerAdapter(listBeneficiary, MainActivity.this,MainActivity.this);
Log.d(TAG,"listBeneficiary size[initObject()] = "+ listBeneficiary.size());
RecyclerView.LayoutManager mLayoutManager = new LinearLayoutManager(getApplicationContext());
recyclerViewBeneficiary.setLayoutManager(mLayoutManager);
recyclerViewBeneficiary.setItemAnimator(new DefaultItemAnimator());
//recyclerViewBeneficiary.addItemDecoration(new DividerItemDecoration(this, DividerItemDecoration.VERTICAL)); // For Vertical line separation
recyclerViewBeneficiary.setHasFixedSize(true);
recyclerViewBeneficiary.setAdapter(beneficiaryRecyclerAdapter);
databaseHelper = new DatabaseHelper(activity);
getDataFromSQLite();
}
/**
* This method is to fetch all user records from SQLite
*/
private void getDataFromSQLite() {
// AsyncTask is used that SQLite operation not blocks the UI Thread.
new AsyncTask<Void, Void, Void>() {
#Override
protected Void doInBackground(Void... params) {
listBeneficiary.clear();
listBeneficiary.addAll(databaseHelper. getAllBeneficiary());
return null;
}
#Override
protected void onPostExecute(Void aVoid) {
super.onPostExecute(aVoid);
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
}.execute();
}
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
newText = newText.toLowerCase();
ArrayList<Beneficiary> newList = new ArrayList<>();
Log.d(TAG,"listBeneficiary size[onQuery] = "+ listBeneficiary.size());
for (Beneficiary beneficiary: listBeneficiary) {
String name = beneficiary.getTitle().toLowerCase();
if (name.contains(newText))
newList.add(beneficiary);
}
beneficiaryRecyclerAdapter.setFilter(newList);
return true;
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.menu_activity_main,menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search by title");
searchView.setOnQueryTextListener(this);
searchView.setIconified(false);
return true;
}
#Override
public boolean onLongClick(View v) {
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_action_mode);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorActionMode));
counter_text_view.setVisibility(View.VISIBLE);
counter_text_view.setText("0 items selected");
is_in_action_mode = true;
beneficiaryRecyclerAdapter.notifyDataSetChanged();
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
return true;
}
public void clearActionMode(){
is_in_action_mode = false;
toolbar.getMenu().clear();
toolbar.inflateMenu(R.menu.menu_activity_main);
toolbar.setBackgroundColor(getResources().getColor(R.color.colorPrimary));
getSupportActionBar().setDisplayHomeAsUpEnabled(false); // old = true
counter_text_view.setText(getString(R.string.app_name)); // New,good
counter = 0;
selection_list.clear();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if (item.getItemId()==R.id.item_delete){
for (Beneficiary contact : selection_list) { //New
listBeneficiary.remove(contact); //New
databaseHelper.deleteSelectedItems(contact.getId());
}
beneficiaryRecyclerAdapter.notifyDataSetChanged(); //new
clearActionMode()
}
else if(item.getItemId()== android.R.id.home){
clearActionMode();
beneficiaryRecyclerAdapter.notifyDataSetChanged();
}
return true;
}
Intent intent = new Intent(this, AccountDetailActivity.class);
Uri currentUri =
ContentUris.withAppendedId(BeneficiaryEntry.CONTENT_URI, id);
intent.setData(currentUri);
startActivity(intent);
}
}
Inside BeneficiaryRecyclerAdapter
public void setFilter(ArrayList<Beneficiary> newList) {
listBeneficiary = new ArrayList<>();
listBeneficiary.addAll(newList);
notifyDataSetChanged();
}
At first the searchView works great many times but after I delete some row it doesn't respond. I have checked using Log.d, the problem is onQueryTextChange(String newText) is not getting any value but works after the mainActivity is resumed. So please let find my mistake.
Try to add
MenuItem menuItem = toolbar.getMenu().findItem(R.id.action_search);
SearchView searchView = (SearchView) menuItem.getActionView();
searchView.setQueryHint("Search by title");
searchView.setOnQueryTextListener(this);
to clearActionMode().
I am trying to implement tab functionality in an Android browser. I tried to save the webpage in a cache, but I can't figure out how to save multiple of them and load them when the user switches tabs. How could I implement this?
I would like to save the current webpage in a cache when the user wants to add a new tab and open Main_activity, and then next time when the user switches tabs, the current webpage should get saved in a cache, and the intended webpage of the intended tab gets loaded in the webview. Now the issue is, I don't know how to handle multiple webpages in a cache, and select which one to load when.
My code consists of two activities, main_activity with some icons and webView_activity with a simple webview. I am using a custom dialog box with a ListView in it, so I will need to add new rows for new tabs and edit them when tabs are switched.
Here is my main_activity
public class MainActivity extends AppCompatActivity {
ImageView yt,google,gm,twitter;
SearchView g_search;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
g_search = (SearchView) findViewById(R.id.g_search);
g_search.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
yt = (ImageView) findViewById(R.id.yt);
google = (ImageView) findViewById(R.id.google);
gm = (ImageView) findViewById(R.id.gm);
twitter = (ImageView) findViewById(R.id.twitter);
yt.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.youtube.com");
startActivity(i);
}
});
google.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.google.com");
startActivity(i);
}
});
gm.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.gmail.com");
startActivity(i);
}
});
twitter.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("shortcut","https://www.twitter.com");
startActivity(i);
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m1, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.menu_search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
Intent i = new Intent(MainActivity.this,webview1.class);
i.putExtra("query",query);
startActivity(i);
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
return false;
}
});
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_new_tab){
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(MainActivity.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(MainActivity.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
boolean doubleBackToExitPressedOnce = false;
#Override
public void onBackPressed() {
if (doubleBackToExitPressedOnce) {
super.onBackPressed();
return;
}
this.doubleBackToExitPressedOnce = true;
Toast.makeText(this, "Please click BACK again to exit", Toast.LENGTH_SHORT).show();
new Handler().postDelayed(new Runnable() {
#Override
public void run() {
doubleBackToExitPressedOnce=false;
}
}, 2000);
}
}
Here is my web_view activity
public class webview1 extends AppCompatActivity {
CustomWebView web1;
String search_q,shortcut;
FloatingActionButton fab;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_webview1);
web1 = (CustomWebView) findViewById(R.id.web1);
web1.setGestureDetector(new GestureDetector(new CustomGestureDetector()));
web1.setWebViewClient(new WebViewClient(){
#Override
public void onReceivedError(final WebView view, int errorCode, String description,
final String failingUrl) {
fragmentManager.beginTransaction()
.replace(R.id.container, new blankState())
.commit();
super.onReceivedError(view, errorCode, description, failingUrl);
}
});
registerForContextMenu(web1);
// web1.getSettings().setRenderPriority(WebSettings.RenderPriority.HIGH);
web1.getSettings().setJavaScriptEnabled(true);
web1.getSettings().setBuiltInZoomControls(true);
web1.getSettings().setDisplayZoomControls(false);
web1.getSettings().setLoadWithOverviewMode(true);
web1.getSettings().setUseWideViewPort(true);
search_q=getIntent().getStringExtra("query");
shortcut=getIntent().getStringExtra("shortcut");
bottomNavigationView = (BottomNavigationView) findViewById(R.id.navigation);
getSupportActionBar().setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM);
getSupportActionBar().setCustomView(R.layout.custom_toolbar);
ImageView action_back = (ImageView) findViewById(R.id.action_back);
action_back.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
onBackPressed();
}
});
BottomNavigationViewHelper.disableShiftMode(bottomNavigationView);
bottomNavigationView.setVisibility(GONE);
fab = (FloatingActionButton) findViewById(R.id.fab);
fab.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// code for launching new tab here
}
});
web1.setWebChromeClient(new WebChromeClient(){
public void onProgressChanged(WebView view, int progress ){
frame_layout.setVisibility(View.VISIBLE);
progress_bar.setProgress(progress);
if(progress==100){
frame_layout.setVisibility(GONE);
srl.setRefreshing(false);
}
super.onProgressChanged(view, progress);
}
});
progress_bar.setProgress(0);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
if(item.getItemId()==R.id.action_url){
ShowUrlDialog();
return true;
}
if(item.getItemId()==R.id.action_home){
Intent i = new Intent(webview1.this,MainActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_new_tab){
// code to launch new tab here
}
if(item.getItemId()==R.id.action_incognito_mode){
}
if(item.getItemId()==R.id.action_bookmarks){
}
if(item.getItemId()==R.id.action_history){
}
if(item.getItemId()==R.id.action_downloads){
}
if(item.getItemId()==R.id.action_settings){
Intent i = new Intent(webview1.this,SettingsActivity.class);
startActivity(i);
}
if(item.getItemId()==R.id.action_about){
Intent i = new Intent(webview1.this,about.class);
startActivity(i);
}
return super.onOptionsItemSelected(item);
}
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
// Inflate menu to add items to action bar if it is present.
inflater.inflate(R.menu.m2, menu);
// Associate searchable configuration with the SearchView
return true;
}
#Override
public void onBackPressed() {
if (web1.canGoBack()) {
web1.goBack();
} else {
super.onBackPressed();
}
}
}
This is below code I am using in my activity.
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
getWindow().requestFeature(Window.FEATURE_INDETERMINATE_PROGRESS);
setContentView(com.c2info.eDawa.R.layout.hll_layout);
AppController.logite("Activity", "HllActivity");
final Toolbar toolbar = (Toolbar) findViewById(com.c2info.eDawa.R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayShowHomeEnabled(true);
getSupportActionBar().setIcon(R.mipmap.app_launcher);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater menuInflater = getMenuInflater();
menuInflater.inflate(com.c2info.eDawa.R.menu.menu_hll, menu);
final MenuItem searchItem = menu.findItem(com.c2info.eDawa.R.id.action_search);
searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
if (searchView != null)
searchView.clearFocus();
return true;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 2) {
getSearchData(newText); // this is the service
}
}
return false;
}
});
return super.onCreateOptionsMenu(menu);
}
In on preExecute i am using
this.setProgressBarIndeterminateVisibility(Boolean.TRUE);
In on postexecute i am using
this.setProgressBarIndeterminateVisibility(Boolean.FALSE);
But progressbar is not showing can anyone help. Thanks in advance.
I have searchView on actionbar and I here is codes for it
public class container extends AppCompatActivity {
private ListView drawerList;
private DrawerLayout drawerLayout;
private Toolbar toolbar;
private ActionBarDrawerToggle toggle;
private TextView textContainer, titleContainer;
private ImageView imageContainer;
private drawerAdapter adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_container);
toolbar = (Toolbar) findViewById(R.id.mainToolbar);
setSupportActionBar(toolbar);
toolbar.setTitleTextColor(0xffffffff);
titleContainer = (TextView) findViewById(R.id.containerTitle);
textContainer = (TextView) findViewById(R.id.textContainer);
imageContainer = (ImageView) findViewById(R.id.imageContainer);
titleContainer.setText(R.string.UtrujjTitle);
textContainer.setText(R.string.UtrujjContent);
imageContainer.setImageResource(R.drawable.utrujj);
final Animation animation = AnimationUtils.loadAnimation(this, android.R.anim.fade_in);
drawerLayout = (DrawerLayout) findViewById(R.id.mainDrawer);
drawerList = (ListView) findViewById(R.id.drawerList);
final SearchView searchView = (SearchView)findViewById(R.id.searchable);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
Spannable spannable = new SpannableString(newText);
spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 100, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textContainer.setText(spannable);
}
return false;
}
});
and in the end I added these overrides
#Override
public boolean onPrepareOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search, menu);
return super.onPrepareOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()){
case R.id.searchable:
return false;
default:
break;
}
return super.onOptionsItemSelected(item);
}
search.xml
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto">
<item android:id="#+id/setting"
android:icon="#drawable/ic_setting"
app:showAsAction="ifRoom"
android:title="#string/setting"/>
<item android:id="#+id/searchable"
android:icon="#android:drawable/ic_menu_search"
app:showAsAction="always"
app:actionViewClass="android.support.v7.widget.SearchView"
android:title="#string/search"/>
</menu>
when activity start I get this error in logcat
Unable to start activity ComponentInfo{com.example.tina.tibbenabvi/com.example.tina.tibbenabvi.container}: java.lang.NullPointerException: Attempt to invoke virtual method 'void android.widget.SearchView.setOnQueryTextListener(android.widget.SearchView$OnQueryTextListener)' on a null object reference
====================================================
This view It's a menu item so you should initialize onCreateOptionsMenu().
Example:
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
// Associate searchable configuration with the SearchView
SearchManager searchManager =
(SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView =
(SearchView) menu.findItem(R.id.search).getActionView();
searchView.setSearchableInfo(
searchManager.getSearchableInfo(getComponentName()));
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
#Override
public boolean onQueryTextSubmit(String query) {
return false;
}
#Override
public boolean onQueryTextChange(String newText) {
if (newText.length() > 0) {
Spannable spannable = new SpannableString(newText);
spannable.setSpan(new BackgroundColorSpan(Color.YELLOW), 0, 100, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
textContainer.setText(spannable);
}
return false;
}
});
return true;
}
EDIT
Manifest file:
<activity ... >
...
<meta-data android:name="android.app.searchable"
android:resource="#xml/searchable" />
</activity>
Create res/xml/searchable.xml file:
<?xml version="1.0" encoding="utf-8"?>
<searchable xmlns:android="http://schemas.android.com/apk/res/android"
android:label="#string/app_name"
android:hint="search..." />
Create a Searchable Activity
public class SearchResultsActivity extends Activity {
#Override
public void onCreate(Bundle savedInstanceState) {
...
handleIntent(getIntent());
}
#Override
protected void onNewIntent(Intent intent) {
...
handleIntent(intent);
}
private void handleIntent(Intent intent) {
if (Intent.ACTION_SEARCH.equals(intent.getAction())) {
String query = intent.getStringExtra(SearchManager.QUERY);
//use the query to search your data somehow
}
}
...
}
And add it in the manifest file:
<activity android:name=".SearchResultsActivity" ... >
...
<intent-filter>
<action android:name="android.intent.action.SEARCH" />
</intent-filter>
...
</activity>
Info from:
http://developer.android.com/intl/es/training/search/setup.html
I've noticed that when I'm using action bar in my apps, there is a blank screen showing for couple of seconds when I start the app, then the activity layout is loaded. Does anyone know how can I resolve this?
If I dont use action bar this blank scren is now showing
Here is an example acyivity that I have:
public class Login extends Activity implements OnClickListener {
private Button signInFacebook;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.login);
initWidgets();
}
private void initWidgets() {
getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.drawable.nav_bg));
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
signInFacebook = (Button) findViewById(R.id.login_fb);
signInFacebook.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.login_fb:
intent = new Intent(this, ChangePassword.class);
startActivity(intent);
break;
}
}
}
I dont get any erros or warnings
Just add this line in your launcher activity
android:theme="#android:style/Theme.NoTitleBar" like below example
<activity
android:name="com.example.app.Login"
android:label="#string/app_name"
android:theme="#android:style/Theme.NoTitleBar" >
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
Use requestWindowFeature
public class Login extends Activity implements OnClickListener {
private Button signInFacebook;
#SuppressLint("NewApi")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
setContentView(R.layout.login);
initWidgets();
}
private void initWidgets() {
getActionBar().setBackgroundDrawable(
getResources().getDrawable(R.drawable.nav_bg));
getActionBar().setDisplayShowHomeEnabled(false);
getActionBar().setDisplayShowTitleEnabled(false);
signInFacebook = (Button) findViewById(R.id.login_fb);
signInFacebook.setOnClickListener(this);
}
#Override
public void onClick(View v) {
Intent intent;
switch (v.getId()) {
case R.id.login_fb:
intent = new Intent(this, ChangePassword.class);
startActivity(intent);
break;
}
}
}
Hope it is useful.
For Proper action bar with all functionality like search you can have the below code
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.search_menu, menu);
MenuItem searchItem = menu.findItem(R.id.search_action_provider);
SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
SearchView searchView = (SearchView) MenuItemCompat.getActionView(searchItem);
if (searchView != null) {
searchView.setSearchableInfo(searchManager.getSearchableInfo(getComponentName()));
searchView.setIconifiedByDefault(false);
}
MenuItemCompat.setOnActionExpandListener(searchItem, new OnActionExpandListener() {
#Override
public boolean onMenuItemActionCollapse(MenuItem item) {
return true;
}
#Override
public boolean onMenuItemActionExpand(MenuItem item) {
return true;
}
});
SearchView.OnQueryTextListener queryTextListener = new SearchView.OnQueryTextListener() {
public boolean onQueryTextChange(String newText) {
if (adapter != null) {
adapter.getFilter().filter(newText);
}
return true;
}
public boolean onQueryTextSubmit(String query) {
if (adapter != null) {
adapter.getFilter().filter(query);
}
return true;
}
};
searchView.setOnQueryTextListener(queryTextListener);
return super.onCreateOptionsMenu(menu);
}
In serch.xml you can have
<?xml version="1.0" encoding="utf-8"?>
<item
android:id="#+id/search_action_provider"
android:icon="#drawable/abc_ic_search_api_holo_light"
android:title="#string/abc_action_bar_home_description"
yourapp:actionViewClass="android.support.v7.widget.SearchView"
yourapp:showAsAction="ifRoom|collapseActionView"/>