I am a client side developer that entered recently into an android project.
In client side world we got frameworks like SASS that let us do math operations on variables.
In Android styles resources, we got Variables and Dimensions. My Question is if its possible to achieve that in Android as well.
For example:
dimens.xml
<dimen name="baseFontSize">18sp</dimen>
styles.xml
<style name="heading1">
<item name="android:textSize"> @dimen/baseFontSize * 2.5 </item>
...
</style>
I define a base font size unit, and plays with it along all the app.
If itsn't possible, whats the best practice to achive it using the Android Way.
You could create a main controller to handle all your scale sets.
For example, you have a layout:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<TextView
android:id="@+id/my_text_view"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/hello_world"
android:textSize="16sp" />
</RelativeLayout>
And you wanna scale the text size android:textSize="16sp"
by a scale in dimens.xml
.
Create your scale rate in a dimens.xml
:
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item name="scaleRate" format="float" type="dimen">2.5</item>
</resources>
And after you create you main controller as this:
package com.example.stackoverflowsandbox;
import android.content.Context;
import android.widget.TextView;
public class MyScaleController {
public static void applyTextSizeScale( final Context context, final TextView myTextView ) {
final float currentTextSize = myTextView.getTextSize();
myTextView.setTextSize( currentTextSize * context.getResources().getDimension( R.dimen.scaleRate ) );
}
}
So you use like that:
package com.example.stackoverflowsandbox;
import android.app.Activity;
import android.widget.TextView;
public class MainActivity extends Activity {
@Override
protected void onCreate( final android.os.Bundle savedInstanceState ) {
super.onCreate( savedInstanceState );
this.setContentView( R.layout.activity_main );
final TextView myTextView = ( TextView ) this.findViewById( R.id.my_text_view );
MyScaleController.applyTextSizeScale( this, myTextView );
}
}
Now you can create many dimens of scale rate to many screen sizes. What you wann at first time, make math calc in XML file, not will work. But thi way I guess you have best approach.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With