How to Create a Reusable Layout for Your Android Apps - dummies

By Barry Burd

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).

  1. Open your project.

  2. 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.

  3. In Android Studio’s main menu, choose Refactor → Refactor This.

    A pop-up menu containing the Style and Layout options appears.

  4. In the pop-up menu, select Layout.

    An Extract Android Layout dialog box appears.

  5. 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.
    The Extract Android Layout dialog box.
  6. 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.

  7. Double-click the reusable_layout.xml branch in the Project tool window.

    Android Studio displays the Designer tool for the reusable_layout.xml file.

  8. Make sure that the Designer tool is in Design mode (as opposed to Text mode).

    In Design mode, you can see the Component tree.

  9. 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.
    The Component tree.

Congratulations! You have a group of widgets that you can use and reuse.