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 my Blog.
In this post, I am going to talk about android share action provider.
What is Share Action Provider?
Share action provider is just a provider for share some action. we just create a that enable data sharing and also to show a submenu with sharing activities if the hosting item is placed on the overflow menu.
In this post, I will show you how can you add this feature in your app. Let's start What we need to do for adding share action provider? It's very simple step. We just need to create a view on menu.xml file add reference it from the java class. That's it.
Code analysis:
1. android:id -> we need an id for the call this view
2. android:title -> set a title, for this view3. app:showAsAction -> here I use "If room". Also available some other action too.
here a short list of action and their work
If room -> if there is enough space on action bar then it will
show always -> it will show this view always in the action bar
never -> for this action, this view will never show
collapseActionView -> This item's action view collapses to a normal menu item.
with text -> this will show the icon with text that defines on android: title on the XML file.
4. actionProviderClass -> here we need to set action provider class. We are working on Share action provider, so we need to set-
android.support.v7.widget.ShareActionProvider
Time for java code-
Create a global variable of Share action Provider Class;
ShareActionProvider myShareActionProvider;
Now come on onCreateOptionsMenu() method initializes this by using getActionProvider() method class of MenuItemCompat
Now you can use this method anywhere you want and update intent for this share action provider.
we just finished all code for adding share action prover. But ...
we can do this also various way, here is another one,
Create a global Variable of ShareActionProvider and initialize it on the on Create menu option (same as previous) now create an Intent where you have data and bind your data on and set this intent to ShareActionProvider variable
see the code:
Intent shareIntent =newIntent(Intent.ACTION_SEND);
shareIntent.setType("text/plain");String s ="welome to Android SketchPad";
shareIntent.putExtra(Intent.EXTRA_TEXT, s);if (myShareActionProvider !=null) {
myShareActionProvider.setShareIntent(shareInten);
}
If you are using loader manager then do this task on the onLoadFinished() method
Fix app crashing:
If you use proguard in your project, then your app will be crashed on release mode. To fix this you need to add below line on the proguard-project.txt
That's it:
That's the ending of today code. now you can add this option to your app. In this post, I just show you a basic tutorial about share action provider. In share action provider I just share text, but you can share image, document, video, audio and much more.
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?
RecyclerView is the more flexible than ListView. Now we all use RecyclerView. But In the RecyclerVIew there is a problem that it's not come with the listener. So we can not handle click event easily. I already post a method to handle click event click here.
Here are an another methods to handle click event. Note: In this post, I just show only some methods where you have to change not full code. Benefits of the methods are you can use this click listener in your activity, not adapter class. If you want to learn about full recycle view code like the adapter and viewHolder class sees this post.
Processes-
1. First, you need to add an interface (you can add interface in separate interface file or declare in on inner class). I add on Adapter class
Note: If you need long click listener then create another method and add on view holder class.
I add a method on interface name OnItemClickListener and add parameter String because we need a string to send another activity.
2.Now modify the default constructor of adapter class
privateClickListener clickListener;
/**
* Constructor for the CustomCursorAdapter
* @param clickListener to handle click event
*/public CustomCursorAdapter(ClickListener clickListener) {
this.clickListener = clickListener;
}
3. Implements view.OnClickListener on viewHolder class. See this
classMyViewHolderextendsRecyclerView.ViewHolderimplementsView.OnClickListener {
// Class variables for the task description and priority TextViewsTextView word;
/**
* Constructor for the TaskViewHolders.
*
* @param itemView The view inflated in onCreateViewHolder
*/privateMyViewHolder(ViewitemView) {
super(itemView);
word = (TextView) itemView.findViewById(R.id.mainRecycleView_TV);
word.setOnClickListener(this);
}
@OverridepublicvoidonClick(Viewv) {
mCursor.moveToPosition(getAdapterPosition());
int wordIndex = mCursor.getColumnIndex(COLUMN_WORD);
String word = mCursor.getString(wordIndex);
//get word from cursor and set it to click listener parameter// we can easily access form click event methods
clickListener.onItemClickListener(word);
}
}
on the Onclick listener method, we take String from array or Cursor and send as our interface method parameter. Now can easily access this string on the main activity.
4. Now time to Use -
implements the interface that's we created earlier,
/** onClick listener for recycler view
* called if click any item on recycler view
* @param word is the selected word from data base
*/
@Overridepublicvoid onItemClickListener(String word) {
Intent intent = new Intent(MainActivity.this, DetailsActivity.class);
intent.putExtra(Intent.EXTRA_TEXT,word);
startActivity(intent);
}
Using adapter
CustomCursorAdapter mAdapter = new CustomCursorAdapter(this);
recyclerView.setAdapter(mAdapter);
Thanks for reading this post.
I hope your code is running well. And you can handle the click event on RecyclerView more easily. But once again full code post of recyclerview is here.
If you have any queries then use comment option I will help you. Happy coding :p
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);
}
}