Software Development Exam  >  Software Development Notes  >  ViewStub in Android with Example

ViewStub in Android with Example - Software Development PDF Download

ViewStub in Android with Example

Last Updated : 22 Aug, 2022

Understanding ViewStub in Android

  • ViewStub in Android serves as an invisible, zero-sized view that allows for the lazy inflation of layout resources at runtime.
  • It is considered a lightweight and straightforward view with no dimensions, providing flexibility for runtime inflation based on specific requirements.
  • When inflated, ViewStub replaces itself in the parent view with the layout resource that has been inflated.

Key Features of ViewStub

  • ViewStub's visibility is only established in the view hierarchy upon invoking setVisibility(int) or inflate().
  • It is particularly useful for scenarios involving complex views such as item details, undo messages, or progress indicators.
  • By loading views only when necessary, ViewStub helps in reducing memory usage and enhances rendering speed.

Comparison with Include Tag

  • Unlike the include tag which incorporates contents from XML files in the layout folder, ViewStub directly loads the view when setVisibility(int) or inflate() is called.
  • While include tag allows separate XMLs for different components like header, footer, left, and right bars, ViewStub focuses on on-demand loading instead of inclusion.
  • Important Methods
    • ViewStub Methods
      • getInflatedId(): This method retrieves the ID of the inflated view. For instance, if a ViewStub is inflated, this method helps in obtaining its unique identifier.
      • setLayoutResource(int layoutResource): By using this method, you can assign a specific layout resource to be inflated when the StubbedView becomes visible or invisible, or when inflate() is called. For example, setting a layout to be inflated within a ViewStub.
      • getLayoutResource(): This method is employed to fetch the layout resource that will replace the current StubbedView with another view upon invoking setVisibility(int) or inflate(). The output of this method will be an integer representing the layout resource.
      • inflate(): When this method is called, it inflates the layout resource identified by getLayoutResource() and substitutes the current StubbedView with the inflated layout resource in its parent view. This is commonly used to dynamically replace views in Android layouts.
      • setVisibility(int visibility): Sometimes, there is a necessity to toggle the visibility of a view between invisible and visible states. This method enables you to control the visibility of the ViewStub.
      • setOnInflateListener(OnInflateListener inflateListener): By utilizing this method, you can specify an inflate listener to be notified once the ViewStub successfully inflates its layout resource. This can be useful for executing actions after the inflation process is completed.

Attributes of ViewStub

AttributesDescription
idTo uniquely identify a ViewStub
inflatedTo set the id of the inflated View. This can be done programmatically using the setInflatedId() method.
layoutTo supply an identifier for the layout resource to inflate when the ViewStub becomes visible or when forced to do so. This can be set programmatically using the setLayoutResource(int) method.

Example

A sample GIF is provided below to help you understand the concepts discussed in this article.

  • Step by Step Implementation

  • Step 1: Creating a New Project in Android Studio

    To start a new project in Android Studio, you can follow the steps outlined in the guide on creating a project in Android Studio. This guide offers instructions in both Java and Kotlin programming languages for Android development.

    Example: You can create a new project by selecting "File" > "New" > "New Project" in Android Studio and then following the setup wizard.

  • Step 2: Adding an Image to the Drawable Folder

    In this step, you will place an image in the drawable folder of your app. Different resolutions may require images of varying sizes, which can be organized under different drawable folders within the 'res' directory.

    Example: You can add an image by copying it into the 'drawable' folder in your project's resources directory.

    ViewStub in Android with Example - Software Development
  • Step 3: Working with XML Files

    Proceed to the 'activity_main.xml' file, which defines the user interface (UI) of your project. Below is a snippet of code from the 'activity_main.xml' file with explanatory comments included.

    Example: In the XML file, you can define the layout of your app's main activity using various XML tags such as LinearLayout, Button, and ViewStub.

    • Ensure that the XML file reflects the desired layout and design of your app's main screen.
    • Utilize LinearLayout to arrange UI elements vertically or horizontally.
    • Buttons can be added to trigger specific actions within the app.
    • ViewStub can be used to optimize app performance by inflating layouts only when needed.
  • Create a New Layout XML File

    To create a new layout XML file, navigate to the 'res' > 'layout' directory in your app, right-click, select 'New' > 'XML' > 'Layout XML file', and name the file as 'custom_viewstub'.

    Example: You can create a new XML layout file by right-clicking on the 'layout' folder, selecting 'New', then 'XML', and finally 'Layout XML file' in Android Studio.

Creating a Custom Layout XML File

  • Create a new XML file for the layout by navigating to app > res > layout and right-clicking to select New > XML > Layout XML file. Name this file custom_viewstub.
  • Within the XML file, define a LinearLayout with match_parent width and height attributes, and a vertical orientation.
  • Include an ImageView with a width of wrap_content, height of 200dp, and centered gravity, referencing an image named cryptocurrency.
  • Add a TextView with attributes for width, height, gravity, text content (e.g., "CRYPTOCURRENCY"), and text color.

Working with the MainActivity File

Step 4:

Open the MainActivity File and examine the provided code snippet below. The code includes comments to aid in understanding.

  • KotlinJava

Programming in Android Using ViewStub

  • Kotlin
  • Java

ViewStub in Android Programming

  • Introduction to ViewStub: ViewStub is a lightweight and efficient way to lazily inflate layout resources at runtime.
  • Implementation in Android: In Android programming, ViewStub is commonly used to dynamically load views without inflating them until they are needed.
  • Usage in User Interface: ViewStub helps improve app performance by deferring the inflation of complex layouts until they are required.
  • Example: For instance, consider an app with a profile page that includes sections for personal information, photos, and settings. Using ViewStub, these sections can be loaded only when the user navigates to them, reducing memory usage and improving responsiveness.
importandroid.app.Activityandroid.os.Bundleandroid.view.Viewandroid.view.ViewStubandroid.widget.Button
class MainActivity : Activity() {private lateinit var simpleViewStub: ViewStublateinit var showButton: Buttonlateinit var hideButton: Button
override fun onCreate(savedInstanceState: Bundle?) {super.onCreate(savedInstanceState)setContentView(R.layout.activity_main)
// get the reference of ViewStubsimpleViewStub = findViewById(R.id.viewStubToLearn)simpleViewStub.inflate()
// get the reference of show buttonshowButton = findViewById(R.id.showButtonForViewStub)
// get the reference of hide buttonhideButton = findViewById(R.id.hideButtonForViewStub)
// perform click event on show buttonshowButton.setOnClickListener {simpleViewStub.visibility = View.VISIBLE}
// perform click event on hide buttonhideButton.setOnClickListener {simpleViewStub.visibility = View.GONE}

MainActivity Class Overview

  • The MainActivity class extends AppCompatActivity.
  • It includes references to various UI elements like ViewStub and Button.
  • The class demonstrates the use of ViewStub to dynamically inflate layouts.

Key Components of MainActivity

  • ViewStub: This class is used to dynamically include layout elements at runtime. For example, consider a scenario where you have a complex or heavy layout that you want to load only when needed to improve performance.
  • Button: Buttons are interactive UI components that users can click to trigger actions. In this context, buttons are used to control the visibility of the ViewStub.

Understanding the onCreate Method

  • The onCreate method is a crucial part of an Android activity lifecycle. It is called when the activity is starting.
  • Within onCreate, the layout for the activity is set using setContentView, which defines the UI of the activity based on the XML layout file.
  • In the provided code snippet, the onCreate method initializes various UI elements and sets up click event listeners for the buttons.

Button Click Events

  • When the Show Button is clicked, the ViewStub becomes visible, displaying the dynamically inflated layout.
  • Conversely, clicking the Hide Button sets the visibility of the ViewStub to View.GONE, effectively hiding it from the user interface.

In summary, the MainActivity class showcases the utilization of ViewStub for dynamic layout inflation and demonstrates the implementation of button click events to control the visibility of UI elements. Understanding these concepts is fundamental when developing interactive and responsive Android applications.

Output: Running on Emulator

When the project is executed, a similar output to the one demonstrated in the video becomes visible. ViewStub in Android serves as a beneficial feature, enabling significant reduction in memory usage. This feature can be activated by inflation.

Video Player00:0002:23Use Up/Down Arrow keys to adjust volume.

Feeling Confused in the Extensive Realm of Backend Development?

If you find yourself perplexed in the expansive domain of Backend Development, it's perhaps time for a transition! Enroll in our Java Backend Development - Live Course and set forth on a captivating expedition to efficiently master backend development within the scheduled timeline.

What Our Course Offers:
  • Thorough Course Content
  • Guidance from Experts to Enhance Learning Efficiency
  • Practical Engagement with Real-world Projects
  • Established Track Record with 100,000 Successful Achievers

Please Log in to post comments...

LoginLike
The document ViewStub in Android with Example - Software Development is a part of Software Development category.
All you need of Software Development at this link: Software Development
Download as PDF

Top Courses for Software Development

Related Searches

Exam

,

Previous Year Questions with Solutions

,

MCQs

,

ViewStub in Android with Example - Software Development

,

Summary

,

Extra Questions

,

Objective type Questions

,

Important questions

,

pdf

,

Viva Questions

,

ViewStub in Android with Example - Software Development

,

ViewStub in Android with Example - Software Development

,

past year papers

,

study material

,

shortcuts and tricks

,

video lectures

,

Free

,

practice quizzes

,

mock tests for examination

,

Sample Paper

,

Semester Notes

,

ppt

;