How to Create a Reusable Layout for Your Android Apps
Often, the check boxes and buttons in your Android app are useful in more than one situation. You might place these widgets in an app with a confirmation word. You might use the same widgets in a different app with a picture of a pizza below the widgets. One way or another, it’s worth your while to save the layout containing these widgets. You save these widgets in a new layout resource document (a blahblah .xml document in the res/layout directory).
Open your project.
In the preview screen, click in a neutral place inside the vertical linear layout that you created.
Make sure that you see the outline of the layout that contains both check boxes and the button. If you have trouble selecting this layout, you can ignore the preview screen and select the LinearLayout (Vertical) branch in the Component tree.
In Android Studio’s main menu, choose Refactor → Refactor This.
A pop-up menu containing the Style and Layout options appears.
In the pop-up menu, select Layout.
An Extract Android Layout dialog box appears.
In the dialog box’s File Name field, type the name of your new resource document.
Below, you see reusable_layout.xml.
The names of Android’s resource files must not contain capital letters. You can use lowercase letters and underscores. You cannot use Java’s customary “camelCase” naming convention with names like reUsableLayout.xml. And, yes, a layout filename must end with the extension .xml.The Extract Android Layout dialog box.
Click OK to close the dialog box.
The app/res/layout branch in the Project tool window now has a new item. If you named the file as was instructed in Step 5, the branch is labeled reusable_layout.xml.
Double-click the reusable_layout.xml branch in the Project tool window.
Android Studio displays the Designer tool for the reusable_layout.xml file.
Make sure that the Designer tool is in Design mode (as opposed to Text mode).
In Design mode, you can see the Component tree.
Make note of the labels on the branches in the Component tree.
Look for names like checkBox, checkBox2, and button.
To change an element’s id, double-click that element in the preview screen. The resulting pop-up menu has a text field labeled id. Change whatever is entered in that text field.The Component tree.
Congratulations! You have a group of widgets that you can use and reuse.