Joe Paul Joe Paul - 6 months ago 11
Android Question

Apply XML code to multiple xml elements

I'm pretty new to android development and I was wondering if there is a way you can apply xml code to multiple elements. For intance, from a css background you can do the following.

.dog, #cat, .fish {color:#blue}


and the color blue will be applied to the objects dog, cat and fish. This is not only easy to type but also makes your code clean

So I was wondering if the same could be applied to XML/Java code

<EditText
android:hint="dog"
android:textSize="15dp"
/>

<EditText
android:hint="cat"
android:textSize="15dp" />


instead of repeating android:textSize="15dp"

Answer

You can achieve this results by following the styles and themes documentation. Let me give you a quick guide:

  1. First navigate to styles.xml res->value->styles.xml
  2. Type the following:
<style name="YourName">
    <item name="android:textSize">15sp</item>
</style>
  1. Then navigate to xml page which has the code you want to clean up: res->layout->YourCodeName.xml

  2. Do this:

<EditText android:hint="cat" style="@style/YourName" />

<EditText android:hint="dog" style="@style/YourName" />

BTW it's better to use sp for text size not dp read more about android styles and themes here:

  1. http://www.tutorialspoint.com/android/android_styles_and_themes.htm
  2. http://www.vogella.com/tutorials/AndroidStylesThemes/article.html