How To Show Custom Toast In Android?

When it's comes to display light message in response to options performed by app Android platform offers Toast.Toast is a light messages display near the bottom,horizontally centered to the screen.Toast can display maximum two line of message.Toast messages are not clickable and hide automatically after sometime.Toast messages are useful when you don't want to block user interface and want to display messages.
Figure 1. shows "Sending message..." text message,indicating message  has been sending.

Fegure 1. Toast Message. 

Show Toast.

To show Toast you need to first initialize Toast object with one of makeText() methods.makeText() method takes three parameters : the application Context, the message to display and duration for the Toast.this method returns fully initialized Toast object.you can show Toast with show() method.

Following code snipped shows how to show simple toast message.


How To Change Toast Default Position?

Toast by default display near the bottom of the screen,horizontally centered.You can change toast default position with setGravity(int, int, int) method,which takes three parameters: a Gravity constant , a X-position offset and Y-position offset.
Following code snippet shows how to position toast to top right corner of the screen.

If you want to change position of x axis of toast then increase or decrease value of second parameter and if you want to change position of Y-axis of toast then increase of decrease value of third parameter.


How To Display Custom Toast?

When simple toast layout can not fulfill your requirements you can create custom view for toast messages.To create custom toast layout define View layout,in XML file or in you application code and pass the root View object to setView(view) method of the Toast object to set this layout.

Following code snipped shows custom layout for the toast message.
Note : save this layout file as custom_toast.xml

You can see that ID of the LinearLayout element is "custom_toast_container". You must use this ID and ID of XML layout file to inflate the layout.

Following code snippet shows how to inflate and set custom layout for Toast.

First retrieve LayoutInflater object with getLayoutInflater() or from getSystemService()  method.then inflate your custom layout with inflate(int, ViewGroup) method, which take to parameters first is the ID of layout file you want to inflate and second is root View.You can use inflated View to find more View objects in the layout.So lets find and set content for TextView.At last create the Toast object with Toast(Context) and set properties like duration,gravity Then call setView(View) and pass it the inflated custom layout.You can now display toast by calling show() method.

How To Implement Swipe-to-Refresh In Android?

If you are updating you app content automatically and user does not need to do any thing for that.But you can also provide feature to user so that they can request for manual update.For example in video streaming app user can request manual update to get latest videos.
To provide consistence user experience for requesting updates.Android provide swipe-to-refresh design pattern,which allow user to trigger update with vertical swipe gesture.

Add Swipe-to-Refresh To App.

Swipe-to-Refresh design pattern is completely implemented with SwipeRefreshLayout widget.which detects vertical swipe gesture of user.Display distinctive progress bar and call callback method in app.You can add swipe-to-Refresh feature by adding this widget in to you layout file as a parent of RecyclerView , ListView or GridView.
Note : SwipeRefreshLayout only support signle RecyclerView , ListView or GridView as his child.

Following code snipped shows how to add SwipeRefershLayout in layout file containing RecyclerView.


 Add Refresh Action To Action Bar.

 

You should add refresh action in action bar , so that user with disability could trigger manual update with external device like keyboard and D-pads.
Following code snipped shows how to add swipe-to-refresh action to menu overflow area.


Refresh App Content With Refresh Requests.


Respond To User Gesture.

To respond to user's vertical swipe gesture you have to implement SwipeRefreshLayout.OnRefreshListener interface and it's onRefresh() method,OnRefresh() method called when user perform vertical swipe gesture.System automatically shows distinctive progress bar when user perform swipe gesture and you should update app content in onRefresh() method.

Following code snipped shows how to implement SwipeRefreshLayout.OnRefreshListener and update app content when you get refresh request from user's vertical swipe gesture.


Respond To The Action Bar Refresh Action.

When user request manual refresh request from action bar,Android OS calls the onOptionsItemSelected() method.Your app should show progress indicator and update app's data when this method calls.To get callback of menu item selection override onOptionsItemSelected() method.To display SwipeRefreshLayout progress indicator call setRefreshing() method of SwipeRefreshLayout with true value,And once update has finished,call setRefreshing(false) to remove progress indicator.

Following code snippet shows how to respond request action.


How To Get Notify When System UI Visibility Changes In Android?

When ever you hide system bars to give fullscreen experience you should also hide or show other part of you app's UI as per your requirements. i.e. play , pause buttons , game controls etc.
In this post we gonna learn how to listen for system bars hide / show event and make any desired changes accordingly.

To listen for system bars hide / show event,register View.OnSystemUiVisibilityChangeListener() to view.This could be any view you used for controlling navigation visibility.

In Following Code Snipped We Have Registered Listener in Activity's onCreate() method.


It's best precise to sync you UI with system bar visibility changes.You could use this code to hide and show video player controls in sync with status bar hide and show event.

How To Enable Fullscreen Mode in Android?

In many case you would like to give your users full immersive experience of your app,i.e. when user play games , when they see picture or read books or read presentations on slides.In this post we are gonna learn how we can give fullscreen experience to user with different available options in Android.

Fullscreen mode hides system bars (status bar and navigation bar). And user won't be able to access them easily,So don't apply fullscreen mode for some extra screen space for your app.Apply Fullscreen when you think it is necessary.

Fullscreen Options On Android.

In Android you can provide fullscreen experience to your users with following three options.
  1. Lean back
  2. Immersive.
  3. Immersive Sticky.
In all this three options system bar and navigation bar will hide and your user get fullscreen experience of your app.The main different between those option is how your user show status bar and navigation bar again.

Lets Learn More About Each Of  Those Options.

 

1. Lean back

You should use this approach when user will not interacting with screen heavily. i.e. when user      watching a video.User can see status bar and navigation bar by clicking anywhere in the screen and status bar and navigation bar will not hide again automatically.your app has to hide status bar and navigation bar if your app want fullscreen experience again.
You can enable Lean back mode by passing  SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION flags in setSystemUiVisiblility() method.

As you can see in following code snippet.

When user click any where in screen status bar and navigation bar will show and hide automatically. If you want to enable Lean back mode again then call the setSystemUiVisibility() method again with same flags.

As you can see in following code snippet.
System bars will automatically hide after 1 second they show.


2. Immersive

You should use this approach when user will interacting with screen heavily.i.e when user play games, watch images in gallery , read paged book etc.when user need to see system bars.they swipe at any edges where system bars are hidden.In immersive mode system bars only visible with this intended swipe gesture.So that the user's engagement with you app in not disturbed by and other touches and swipe gestures.
You can enable Immersive mode by passing  SYSTEM_UI_FLAG_IMMERSIVE  flag with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION flags in setSystemUiVisibility() method.

As you can see in following code snippet.

In immersive mode if system bars re-appear then they will not be automatically hide , your app needs to set those flags again if your app wants to enable immersive mode again.

As you can see in following code snippet.
System bars will automatically hide after 1 second they show.


3. Immersive sticky

In normal immersive mode if user swipe from edge of screen then system take care of revealing and your app will not know that swipe gesture occurred.If app provide feature in which user needs to swipe from very edge of screen (i.e. drawing app) then you should enable "sticky" immersive mode.
In sticky immersive mode while swipe from very edge of the screen then system bar will appear but they are semi-transparent and hide automatically after some time or as soon as user touches of click anywhere outside the system bars and the touch gesture will passed all the way down to app.
For example in image editing app when user start the drawing from very edge of screen the system bars will appears and drawing also start from that very edge of the screen.
You can enable Immersive sticky mode by passing SYSTEM_UI_FLAG_IMMERSIVE_STICKY flag with SYSTEM_UI_FLAG_FULLSCREEN and SYSTEM_UI_FLAG_HIDE_NAVIGATION flags in setSystemUiVisibility() method.

As you can see in following code snippet.

In immersive sticky mode system bars (status bar and navigation bar ) will hide automatically,and your app will not get any callback about show and hide system bars.

How To Show Content Behind Navigation Bar In Android?

Many time you need to show your app content behind the navigation bar , so your app content does not resize as navigation hide or show.

Figure 1. Transparent Navigation Bar
 
It is very easy to show content behind navigation in Android 4.1 and higher. you only need to set  SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION  flag and you should also set SYSTEM_UI_FLAG_LAYOUT_STABLE  flag it helps app to maintain stable layout. 

As shown in following code snipped.

When you use this approach it may be possible some part of your UI covered with system bars.so be careful and apply proper padding to layout so your UI components not covered by system bars.

How To Hide Navigation Bar In Android ?

In this post we are gonna learn how to hide Navigation Bar.Navigation bar was introduced in Android 4.0 (API level 14). When ever you hide navigation bar you should also hide status bar at the same time.You can learn how to hide status bar HERE.When you hide navigation bar (and status bar) using this approach your app content can use full display space,and user can easily access navigation bar (and status bar).

 
Figure 1. Navigation Bar
You can hide navigation bar using the SYSTEM_UI_FLAG_HIDE_NAVIGATION. As you can see in following code snipped.(In this example we will hide both navigation bar and status bar)

Following are some points which you need to keep in mind when using this approach.

  • When you hide navigation bar (and status bar) using this approach , if user touch anywhere on screen then navigation bar (and status bar) will reappear and not hide again automatically.User interaction clears those flags.
  • Once flags have cleared by any cause,your app needs to set them again if you want to hide system bars again.
  • If you set those flag in activity's onCreate() method and user tab on home then system bars will appears and not hide when user came back in app. Activity's onCreate() method will not call when user reopen app.You can set those flags in onResume() or in onWindowFocusChanged() when you again want to hide system bar user reopen app.
  • setSystemUiVisibility() method only works if it's called from visible view.
  • Any system ui flag set with setSystemUiVisibility() will cleared if user navigate away from app.

How To Show Content Behind The Status Bar?

Many times you end up with tasks in which you have to show app content behind the status bar.
Then you search for the solution on web,copy and paste code from many websites and blogs but you don't get the result you want.
In this simple tutorial we are gonna learn how to show app content behind the status bar.

Figure 1. Show image behind the status bar.
Figure 1. Image behind status bar.

In this approach your content does not resize when status bar show or hide,So you get consistence user experience.
You can show app content behind the status bar using SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN You should also use SYSTEM_UI_FLAG_LAYOUT_STABLE to help your app maintain stable layout.

And remember to set the transparent status bar either in style.xml
<item name="android:statusBarColor">@android:color/transparent</item>
Or set the transparent status bar programmatically:
getWindow().setStatusBarColor(Color.TRANSPARENT) 

As show in following code snipped.


When you use this approach you should careful about your app's UI critical parts ( Action Bar , Default Map Controls etc) are not overlap by system windows.In many cases you can handle this issue by adding android:fitsSystemWindows attribute in your layout xml file with the value set to true.This attribute set the proper padding to parent viewGroup so that you app content draw after that padding and do not overlap by system windows.

For many cases android:fitsSystemWindows works perfectly,but if you want to alter default padding to get your disired layout.You can set public void setOnApplyWindowInsetsListener(View.OnApplyWindowInsetsListener listener)
By passing object of View.OnApplyWindowInsetsListener. Space which occupy by system bars are also know as window insets. Listener will call when system set the window insets you can then use those window insets as your needs.

Official Documentation Says "Set an OnApplyWindowInsetsListener to take over the policy for applying window insets to this view. The listener's OnApplyWindowInsetsListener#onApplyWindowInsets(View, WindowInsets) method will be called instead of the view's onApplyWindowInsets method."

As show in following code snipped.

 


How To Hide Status Bar In Android?

In this post we are going learn how to hide status bar  (and navigation optionally), by hiding status bar you can have more space to show your contact and provide more immersive user experience.
Note : If you hide status bar then you must hide action bar with it.

Figure.1 show app with visible status bar.

 Figure 1.Visible Status Bar.

 Figure 2. show app with hidden status bar, you can see that action bar also hidden, you should never show action bar when status bar is hidden.
Figure 2. Hidden Status Bar.

You can hide status bar on Android 4.1 and higher using setSystemUiVisibility() 
setSystemUiVisibility() set the flag at individual view level and those settings aggregated to window level. If you set UI flag using setSystemUiVisibility()  then you get more granular control over system bar then using WindowManager flags.

 Follow code snippet hide status bar.

You must remember following  points when you use this approach.
  • If UI flag cleared by any activity(i.e. navigating away from activity).Your app must set them again if you want to hide status bar again.
  • Where you set system UI flag matter most.If you hide System Bars in activity's onCreate() method and if user press home button then system bar will appear again.If user reopen app then onCreate() will not called.so system bars remain visible.If you want to persist as user navigate in and out of your activity.Then set UI flags in onWindowFocusChanged() or OnResume().
  • The setSystemUiVisibility() method works only if you call it from view which is visible.
  • If User navigate away then UI flags set with setSystemUiVisibility() is cleared.

How To Dim System Bars On Android?


System Bars on android mains status bar and navigation which drawn by system with your app content.In this tutorial we are gonna dim system bars on Android version 4.0 Android Higher.
When you used this approach you content does not resize but icons in system bar visually recede. And when user touch either status bar nor navigation bar area of the screen both the system bar become fully visible.
Main advantage of this approach is system bars still present but their details are observed. 
This creates immersive experience with easy access of System bars.

Dim Status Bar And Navigation Bar.

You can dim status bar and navigation bar usinSYSTEM_UI_FLAG_LOW_PROFILE  flag. 
As Shown Below. 

As soon as the user touches Status bar or Navigation bar area of the screen.the flag cleared,Resulting fully visible System bars.And If this flag cleared once,then you have to set this flag again if you want dim System bars again.

In Figure 1 we can see gallery image in which navigation bars is dimmed (Gallery Application completely hide status bar it does not dim it). You can see navigation bar right side with small white dot which is present navigation control.


Figure 1. Dimmed System Bars.
 
 You can see same image in Figure 2.But system bars displayed.

Figure 2. Visible System Bars.

 
If you want to programmatically clear flag set with setSystemUiVisibility() , You can do so as follows.

How To Show Activity On Lock Screen In Android?

 

Are you wondering about how to show activity on lock screen on Devices? , If your answer is yes then this simple tutorial is for you.You may have seen that when any application whats app, facebook receive call they display calling activity to receive call even when your phone is lock.
How they do that? ,Well showing activity on lock screen is every easy task.

Lock Screen.


In Android activity class has one called "setShowWhenLocked" , which we can called in other show any activity on lock screen.

Let Look at the method signature.
public void setShowWhenLocked (boolean showWhenLocked)

Specifies whether an Activity should be shown on top of the lock screen whenever the lockscreen is up and the activity is resumed. Normally an activity will be transitioned to the stopped state if it is started while the lockscreen is up, but with this flag set the activity will remain in the resumed state visible on-top of the lock screen. This value can be set as a manifest attribute using R.attr.showWhenLocked.

It's public method , it's returns nothing so it has return type void, and it's take one boolean argument which specificy you want to show activity on lock screen or not.

You can call this method from onCreate method of Activity.

JAVA: 
public void onCreate(Bundle savedInstanceState)
{
        super.onCreate(savedInstanceState);
        //Show Activity On Lock Screen
        setShowWhenLocked(true); 
 
        // load the layout
        setContentView(R.layout.trenyprogrammer_activity); 
}
 
KOTLIN:
override fun onCreate(savedInstanceState : Bundle){
 
        super.onCreate(savedInstanceState)
        //Show Activity On Lock Screen 
        setShowWhenLocked(true) 
 
        // load the layout
        setContentView(R.layout.trenyprogrammer_activity)
} 

It's Easy to show Activity on lock screen.If you like what you read then give comment about this tutorial and other tutorial which you want to learn , Your valuable feedback make our tutorial quality batter.