In this post, I will be talking about the Visibility attribute for Android views. So what are Android Views? Android Views are user interface elements that are drawn onto the screen and that a user can interact with. For example, a button, a textview,and an imageview.
Android view attributes define how an element looks like, such as it's height, width, and color. Think of them as metadata for views. A view's visibility can be set to gone, invisible, or visible, as indicated in the sample code below:
This is a view's visibility value by default. This means that the view will always be displayed on the screen.
As it is default, a view's visibility does not have to be explicitly set to visible. As we can see with the sample below, the textview that displays the infamous "Hello World" is visible on the screen.
When we set textview's visibility attribute to gone,
it will simply not show on the screen and it's space on the layout will be occupied by surrounding elements.
When the view is toggled from gone to visible, surrounding elements will simply make way for the view and the view will ocuppy it's space and show on the screen.
Looking at our sample app below, we can see that the textview is not visible on the screen and it's space is occupied by the buttons.
If a view's visibility is set to invisible, the view will not be displayed, but it will still occupy it's space on a layout. So it might make the layout look a little weird with some extra space in-between elements.
Taking a look back at our sample app, the textview is not shown, but it still occupies it's space. The buttons stay in their positions.
Changing Visibility On The Go
Toggling between the different visibility values can be easily achieved programatically. I have added the functionality of toggling between the different visibility attribute value behind the clicks of the buttons. When the "Gone" button is clicked, we change the visibility value to gone. When the "Invisible" button is clicked, we change the visibility value to invisible. When the "Visible" button is clicked, we simply change the visibility value to visible.
Take a peek below:
Toggling between the different visibility values aids us in showing the user relevant content depending on the activity being carried out on the screen. For example, we can show a loader when making a service call, and then only display the underlying content once we have a response from the server. The android visibility attribute is just one of many attributes that are available for us to use and play around with, so don't be shy to try them out.
A cool post you can check out https://guides.codepath.com/android/Defining-Views-and-their-Attributes.
Thank you to Andrei Lazarev for the amazing cover image take from https://unsplash.com/photos/U47vtNMkyXg