In this post, I am going to cover Android Search View with Recent Search Suggestion.
In a previous post, I already cover Android Material SearchView. In that post, I use a 3rd party library. If you want to use 3rd party library to add search functionality, see this post. Android Material SearchView
But Now I don't want to use any 3rd party library.
In this post, I use:
Search Widget
Let's start:
create a new activity:(In my case, I named it: SearchActivity)
Welcome to this post. In this post, I am going to discuss on Android Splash Screen.
In this whole post, I gonna cover those topics
1. How to create android Splash Screen
2. How to override default color when app launching (windows background)
When you click app icon, the app takes some time to start. To overcome this option android by default show a color until the activity is launched. By default, it is white in color. So later in this post, I will show you how to overcome this situation and how to change this default color.
Let's start-
Create an Activity named it as your choice
now design your layout file. I just provide my XML code.
<?xml version="1.0" encoding="utf-8"?><android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"xmlns:app="http://schemas.android.com/apk/res-auto"xmlns:tools="http://schemas.android.com/tools"android:layout_width="match_parent"android:layout_height="match_parent"app:layout_behavior="@string/appbar_scrolling_view_behavior"tools:context="com.blogspot.shudiptotrafder.soilscience.SplashActivity"tools:showIn="@layout/activity_splash"android:background="?attr/colorPrimary"><ImageViewandroid:id="@+id/splash_imageView"android:layout_width="match_parent"android:layout_height="200dp"app:srcCompat="@drawable/ic_lover"app:layout_constraintStart_toStartOf="parent"android:layout_marginStart="8dp"app:layout_constraintEnd_toEndOf="parent"android:layout_marginEnd="8dp"android:contentDescription="app icon"app:layout_constraintTop_toTopOf="parent"android:layout_marginTop="80dp"tools:ignore="HardcodedText"/><TextViewandroid:id="@+id/splash_app"android:layout_width="wrap_content"android:layout_height="wrap_content"android:text="App Name"app:layout_constraintStart_toStartOf="parent"android:layout_marginStart="8dp"app:layout_constraintEnd_toEndOf="parent"android:layout_marginEnd="8dp"android:layout_marginTop="16dp"android:textSize="30sp"app:layout_constraintTop_toBottomOf="@+id/splash_imageView"/><TextViewandroid:layout_width="wrap_content"android:layout_height="wrap_content"app:layout_constraintTop_toBottomOf="@+id/splash_app"app:layout_constraintStart_toStartOf="parent"android:layout_marginStart="8dp"android:layout_marginEnd="8dp"android:layout_marginTop="16dp"android:id="@+id/splash_appAbout"android:text="This is a complete app"android:textSize="16sp"app:layout_constraintEnd_toEndOf="parent"/></android.support.constraint.ConstraintLayout>
now create an instance of Thread class and in the run methods call sleep methods and pass value 1000 (1000 for 1s, the value of Mille seconds). Don't forget to put this sleep method on try-catch block. and finally, block on try-catch, create an Intent that brings us to MainActivity. At list call finish() method and this activity will be destroyed.
See the code-
That's it. Splash Screen is created successfully. You can run a test for see result.
oh! Your app is not working. I forget one thing that we are using vector drawable. If your app minimum API is 21 then you have no headache. but if you targeting lower API you need to use support library to support vector drawable for lower API. To do that add below line in your build.gradle file
A Bonus for you
I also show you how to animate this splash screen. This is the pretty basic animation example.
Let's do this
create an XML file on res -> anim folder.
splash_screen_animation.xml
In the upper activity code, we don't create view variable, because we don't need that time. But now we need those views add set this animation with those views. Create view and assign it by calling findViewById()
That's it
now you can create a splash screen and also override the loading screen. In this example, I use just the only color but you can also use drawable in the loading time. So it's your choice what you used un your project.
That finished this post.
Why you wasting your time, create an awesome splash screen for your existing or next project?
welcome to this post.In this post we are going to learn about how to use night mode on Android app. you can turn on night mode in your app by using android support library. you can use this option in settings or in the menu item.
Night mode
In this case, I use this on settings. In a past post, we learn how to make app settings you can take a look
Let's start-
First, add new file name colors.xml in values-night folder and some colors-
Note: add this color but you can only just add that's the color you want to override in night mode. Take a look on my values->colors.xml file then you can take a clear look on it.
Now time to change your style- your style might look like this-
<!-- Base application theme. -->
<stylename="AppTheme"parent="Theme.AppCompat.Light.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Now change Theme.AppCompat.Light.DarkActionBar to Theme.AppCompat.DayNight.DarkActionBar. Let's do this-
<!-- Base application theme. -->
<stylename="AppTheme"parent="Theme.AppCompat.DayNight.DarkActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">@color/colorPrimary</item>
<item name="colorPrimaryDark">@color/colorPrimaryDark</item>
<item name="colorAccent">@color/colorAccent</item>
</style>
Look like you complete 50% work Now come to the java code- I am using settings so night is enabled not that's saved in a shared preference. Shared preferences key-
<stringname="switchKey">SwitchKey</string>
Now create a method that is checked is night mode is enable or not. The default value is false-
Now Create a new Methods that's set Night mode in any activity-
Follow those steps-
1. call the newly created methods and save the return value on a boolean.
2 If the value is true the we write AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_YES) on the if condition.
3. If it false then we add AppCompatDelegate.setDefaultNightMode(AppCompatDelegate.MODE_NIGHT_NO)this line.
see the code-
//set night mode for app
private void setNightMode() {
//get from setting check bok preference is true or false
boolean isEnabled = getNightModeEnabled(this);
if (isEnabled) {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_YES);
} else {
AppCompatDelegate.setDefaultNightMode(
AppCompatDelegate.MODE_NIGHT_NO);
}
}
Final Screen short
Day Mode
Night mode
Thank you for reading this post hope you can use this option in your app
Happy coding
Welcome to this post.
Android Material Search view tutorial. In this tutorial, we going to make a project and Implement A search view on the toolbar.
For search view, I use a 3rd party library Material SearchView
we have to do with this project-
1. we set search view on the toolbar.
2. Filter RecyclerView with text input
3. voice search
some bonus- In this project,
1. use SQL database for store data2. use the content provider to access data.
3. use Loaders for load data(Curser loaders).
Let's Start- First, add this line to your build.gradle file and sync gradle.
OK, now time to add a toolbar to the layout. In this case, I add on activity_main.xml
<RelativeLayoutxmlns:android="http://schemas.android.com/apk/res/android"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"tools:context=".MainActivity"android:background="@color/colorPrimary"android:layout_marginBottom="2dp"android:elevation="6dp"><!-- don't forget to set elevation or it look like old action bar--><android.support.v7.widget.Toolbar
android:id="@+id/toolbar"android:layout_width="match_parent"android:layout_height="?attr/actionBarSize"android:background="?attr/colorPrimary"android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar"app:popupTheme="@style/ThemeOverlay.AppCompat.Light" /><br.com.mauker.materialsearchview.MaterialSearchView
android:id="@+id/search_view"android:layout_width="match_parent"android:layout_height="match_parent"style="@style/MaterialSearchViewStyle"/></RelativeLayout>
Note: I will provide GitHub link to this project later in this post
now set all search operation I created a private method and call it on Oncreate-
In this method, we add three listeners to the search view-
1. setOnQueryTextListener
2. setSearchViewListener
3. setOnVoiceClickedListener In listener
1. setOnQueryTextListener is fired when we type text in the search view. In this listener, we have to override two methods name-
i. onQueryTextSubmit
ii. onQueryTextChange
i. onQueryTextSubmit is called when we put the query data with submit button.
after submit-
* build a URI
* call getContentResolver and query database and save it on cursor variable.
* if the cursor is not null and cursor data is more than 0 we have data(Call cursor.getCount())
* so we go to the details activity with intent and set this URI with intent
*close search view
ii. onQueryTextChange is called every time when you write.
So we have to set-
* we are going to update recycler view with type text
* we check the text length is greater than zero
* then we create a selection string variable for cursor query. we use SQL LIKE statement not where statement.
String selection =MainWordDBContract.Entry.COLUMN_WORD+" like ? ";
* add also selection Argument-
String[] selectionArg =newString[]{newText+"%"};
* same way to get cursor and same condition for update UI as onQueryTextSubmit
Let's see the code-
searchView.setOnQueryTextListener(newMaterialSearchView.OnQueryTextListener() {
@OverridepublicbooleanonQueryTextSubmit(Stringquery) {
Uri uri =MainWordDBContract.Entry.buildUriWithWord(query.toUpperCase());
Cursor cursor = getContentResolver().query(uri,
MainActivity.projection,null,null,null);
if (cursor !=null&& cursor.getCount() >0){
Intent intent =newIntent(MainActivity.this,
DetailsActivity.class);
intent.setData(uri);
startActivity(intent);
searchView.closeSearch();
searchView.setCloseOnTintClick(false);
}
if (cursor !=null){
cursor.close();
}
returntrue;
}
@OverridepublicbooleanonQueryTextChange(StringnewText) {
if (newText.length() >0){
String selection =MainWordDBContract.Entry.COLUMN_WORD+" like ? ";
//if you are try to search from any position of word//then use//String[] selectionArg = new String[]{"%"+newText+"%"};//if you try to search from start of word the use this lineString[] selectionArg =newString[]{newText+"%"};
Cursor cursor = getContentResolver().query(MainWordDBContract.Entry.CONTENT_URI,
MainActivity.projection,selection,selectionArg,null);
if (cursor !=null&& cursor.getCount() >0){
mAdapter.swapCursor(cursor);
}
returntrue;
} else {
returnfalse;
}
}
});
Now add the setSearchViewListener listener and there are also two methods.
* if search view is open then hide the fab
* if searchView close the show the fab again Code-
On the last, we have added setOnVoiceClickedListener if you are using this option. for this, I write another method name askSpeechInput so let's see the code one by one- the listener-
privatevoid askSpeechInput() {
Intent intent =newIntent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE_MODEL,
RecognizerIntent.LANGUAGE_MODEL_FREE_FORM);
intent.putExtra(RecognizerIntent.EXTRA_LANGUAGE, Locale.getDefault());
intent.putExtra(RecognizerIntent.EXTRA_PROMPT,
"Speak your desire word");
try {
startActivityForResult(intent, MaterialSearchView.REQUEST_VOICE);
} catch (ActivityNotFoundException a) {
a.printStackTrace();
slet("Activity not found", a);
Toast.makeText(this, "Sorry Speech To Text is not "+"supported in your device", Toast.LENGTH_SHORT).show();
}
}
one more method to go. we are now overriding onActivityResult for getting voice input-
@Override
protected void onActivityResult(int requestCode, int resultCode, Intentdata) {
if (requestCode ==MaterialSearchView.REQUEST_VOICE && resultCode ==RESULT_OK) {
ArrayList<String> matches =data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
if (matches !=null && matches.size()>0) {
String searchWrd = matches.get(0);
if (!TextUtils.isEmpty(searchWrd)) {
//Todo more accure on settings
searchView.setQuery(searchWrd, false);
Uri uri =MainWordDBContract.Entry.buildUriWithWord(searchWrd.toUpperCase());
Cursor cursor = getContentResolver().query(uri,
MainActivity.projection,null,null,null);
if (cursor !=null && cursor.getCount()>0){
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.setData(uri);
startActivity(intent);
searchView.closeSearch();
searchView.setCloseOnTintClick(false);
}
if (cursor != null){
cursor.close();
}
}
}
return;
}
super.onActivityResult(requestCode, resultCode, data);
}
voice search screen short:
Material Search View (voice search)
add this line onResume method
searchView.activityResumed();
and last one-
@Overridepublicboolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will// automatically handle clicks on the Home/Up button, so long// as you specify a parent activity in AndroidManifest.xml.switch (item.getItemId()) {
caseR.id.action_search:// Open the search view on the menu item click.
searchView.openSearch();
returntrue;
default:return super.onOptionsItemSelected(item);
}
}