Mishel
Mishel

Reputation: 169

Get rid of attributes oversupply in xml

How to minimize count of attribute names in xml layout?

For example I have this one, full of necessary things:

<ScrollView
android:id="@+id/scroll"
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:scrollbars="none"
android:layout_height="wrap_content"
android:paddingBottom="@dimen/activity_vertical_margin"
android:paddingLeft="@dimen/activity_horizontal_margin"
android:paddingRight="@dimen/activity_horizontal_margin"
android:paddingTop="@dimen/activity_vertical_margin"
app:layout_behavior="@string/appbar_scrolling_view_behavior"
tools:context=".MainActivity"
tools:showIn="@layout/activity_main">

Thanks !

Upvotes: 1

Views: 25

Answers (1)

Cory Charlton
Cory Charlton

Reputation: 8938

Use a style.

A style is a collection of properties that specify the look and format for a View or window. A style can specify properties such as height, padding, font color, font size, background color, and much more. A style is defined in an XML resource that is separate from the XML that specifies the layout.

Styles in Android share a similar philosophy to cascading stylesheets in web design—they allow you to separate the design from the content.

In your styles.xml in the values folder:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style name="YourScrollView" >
        <item name="android:layout_width">match_parent</item>
        <item name="android:scrollbars">none</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:paddingBottom">@dimen/activity_vertical_margin</item>
        <item name="android:paddingLeft">@dimen/activity_horizontal_margin</item>
        <item name="android:paddingRight">@dimen/activity_horizontal_margin</item>
        <item name="android:paddingTop">@dimen/activity_vertical_margin</item>
    </style>
</resources>

Then your layout becomes:

<ScrollView
    android:id="@+id/scroll"
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    app:layout_behavior="@string/appbar_scrolling_view_behavior"
    tools:context=".MainActivity"
    tools:showIn="@layout/activity_main"
    style="@style/YourScollView"
    >

Upvotes: 1

Related Questions