Lahiru Chandima
Lahiru Chandima

Reputation: 24068

Wrap existing layout element in another layout with Android Studio

When designing activity layouts, I frequently encounter cases where I need to wrap an existing element in a layout. For an example, say I have following layout structure.

<LinearLayout android:orientation="vertical">
    <TextView />
    <TextView />
</LinearLayout>

And I want to wrap one of the TextViews in another LinearLayout to get following.

<LinearLayout android:orientation="vertical">
    <LinearLayout android:orientation="horizontal">
        <TextView />
        <SomeNewElement />
    </LinearLayout>
    <TextView />
</LinearLayout>

Is there an easy way to achieve this, preferably through the Android Studio designer?

Upvotes: 3

Views: 2141

Answers (2)

J Michael
J Michael

Reputation: 109

Yes, you may easily customize your own wraps.

Press Ctrl+Alt+S to get to Settings. Navigate to Editor>Live Templates>surround. I use surround here by way of example, but you can navigate to the most logical section for you. You'll see a few examples already there for you. Please note the use of the wildcard, $Selections, which represents the entirety of the code you'll wrap.

Now click the plus icon to your right in the settings pane to begin adding your own. In the lower half of the dialog, you'll enter your context in the Template Text area, with the keyboard shortcut key sequence you prefer. Please also note the Applicable in... change link that provides programming-language options specific to your desired wrap.

This nifty feature allows you to provide shortcuts in specific context, which won't interfere with other languages you may be programming - they could be using the same shortcuts.

Click Apply for edits. You may also duplicate, right-click and select Move if you'd like to add it to another collection heading within Live Templates. When you're done, click the OK button.

Back in Android Studio code line editing, while code to be wrapped is selected, pressing Ctrl+Alt+T immediately displays the context menu to select the enclosing coding you've provided for, with its shortcut.

Additionally, a valuable quick tip from StackOverflow's Ali Nem (link below) shows pressing Ctrl+W a couple of times in editor conveniently selects the entire code block. You'll find out that it works much better in comparison with "mousing" your selections.

See: Shortcut to select a line of code in Android Studio

Upvotes: 1

DavidL
DavidL

Reputation: 1150

Your can drag your new layout from the Element list (Palette) into the Component Tree (as a child of the top-level layout).

Then you just have to drag and drop your textView into the new layout.

Upvotes: 2

Related Questions