Keep Your Powder DRY
Most of us are familiar with the DRY (Don't Repeat Yourself) Principle, the last element of the SOLID set of principles.
Here's how you can apply it in Android Layouts to set a property value for all widgets of a certain type in one place, so that if you need/want to change it later, you only need do it in one place, rather than revisit oodles of widgers within possibly multiple Layout files:
- Open the \[appName]\app\src\main\res\values\styles.xml file.
If you don't have one (styles.xml is created automatically for you there if you are using Droidio), create it at that spot, and add this to it to begin with (in
Droidio, it's already there):
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
</style>
</resources>
- Verify that "
AppTheme
" (you can change the name to "YanquiGoogleDandy
" or whatever if you want to) is referenced in AndroidManifest.xml like so:
android:theme="@style/AppTheme"
In context, that is:
<application
android:allowBackup="true"
android:icon="@drawable/ic_launcher"
android:label="@string/app_name"
android:theme="@style/AppTheme" >
<activity
. . .
- Now you can add a style in styles.xml, like so:
<style name="NavyTextViewStyle" parent="android:Widget.TextView">
<item name="android:textColor">#000080</item>
</style>
- Now add the reference to it in the "AppTheme" section like so:
<item name="android:textViewStyle">@style/NavyTextViewStyle</item>
In context:
<resources>
<style name="AppTheme" parent="Theme.AppCompat.Light.DarkActionBar">
<item name="android:textViewStyle">@style/NavyTextViewStyle</item>
</style>
<style name="NavyTextViewStyle" parent="android:Widget.TextView">
<item name="android:textColor">#000080</item>
</style>
</resources>
So now AppTheme
activates the "NavyTextViewStyle
" style you added, and since the app uses the "AppTheme
" theme, all EditText
widgets will inherit the color value ("#000080
", or Navy
), as can be seen here:
What if you don't want your global value to take effect in a particular case? Just override it by explicitly declaring a different value there, such as this, to use dark red instead:
android:textColor="#8B0000"
Stay Warm and DRY
Now you can use that same methodology to globally set other values for any widgets you use. No need to thank me - just "pay it forward!"