I made my custom component just putting few TextViews together. Now I want to be able to init my custom control directly from code, passing text sizes independently for each of of TV's
My attributes definition:
<resources>
<declare-styleable name="BasicGauge">
<attr name="valueTextSize" format="dimension" />
<attr name="titleTextSize" format="dimension" />
<attr name="unitsTextSize" format="dimension" />
</declare-styleable>
</resources>
Sample initialization of component:
<pl.com.digita.BikeComputerUi.customviews.BasicGauge
android:id="@+id/basicGauge1"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:padding="10dp"
valueTextSize="40sp">
</pl.com.digita.BikeComputerUi.customviews.BasicGauge>
How I try to read those attributes in component's constructor:
final int N = typedArray.getIndexCount();
for (int i = 0; i < N; i++) {
int attribute = typedArray.getIndex(i);
switch (attribute) {
case R.styleable.BasicGauge_valueTextSize:
valueTextSize = typedArray.getString(attribute);
break;
case R.styleable.BasicGauge_titleTextSize:
titleTextSize = typedArray.getString(attribute);
break;
case R.styleable.BasicGauge_unitsTextSize:
unitsTextSize = typedArray.getString(attribute);
break;
}
typedArray.recycle();
}
Problem: After creation all of my values are still null. 40sp is exactly my desired value.
A few things to say :
After that, it's not a very good idea to get a string, android offers more powerfull solution to deal with dimensions :
int unitsTextSize = typedArray.getDimensionPixelSize(R.styleable.BasicGauge_unitsTextSize, textSize);
then there are some subtleties :
paint.setTextSize(unitTextSize):
textView.setTextSize(TypedValue.COMPLEX_UNIT_PX, unitTextSize);
The difference comes from what is called "raw pixels" (unscaled according to density, just raw) and "scaled pixels" (the opposite).