How to re-use layouts where you want, using include tag

Updated 6 July 2023

Save

Reusing layouts are particularly powerful as it allows you create reusable complex layouts.

Whenever we’re creating complex layouts and more featured layouts, then we have to add many ViewGroup’s and Views. But, our this complex layout is the cause of slowness and rendering problem in our application. If we want to Create optimized and easily understandable layouts then android give us the power to make it by using <include /> tag.

Let us suppose that, we want to add header text in all activity in the entire application. Then we can just declare it in all the layouts files as required. But if we have to change the header text or small modification then what happened?
we have to perform changes in all XML file where we have used header text, which costs a lot of time.

So,

In android, we can create re-usable UI layouts by putting them into an extra XML and then by <include/> we can re-use that extra XML where we want.

In this tut, we’ll see how to use the <include /> tag in our XML file to avoid complexity and replication of code in layouts.

 

How to use it?

We just have to create an XML file which we want to reuse. In our example, the name of reusable XML file is header.xml.

header.xml

Above, we have simply created a reusable layout. And use this header.xml file in all your activity/fragment layout files by <include />.

 

where to use it?

Here, we have created an activity_main, where we are using that header.xml layout by <include />.

activity_main.xml

Here we have used the headerText of the header.xml layout using <include />.

If we want to set headertext programatically then

in your MainActivity.java,

And if we have include the same layout multiple times like this

Then we can access the textViews or views by using following code snippets

 

 

 

 

 

 

 

 

 

 

author
. . .

Leave a Comment

Your email address will not be published. Required fields are marked*


1 comments

  • ekta
  • Start a Project


      Message Sent!

      If you have more details or questions, you can reply to the received confirmation email.

      Back to Home