I have set multiple flag attributes in an android custom textview, how do I recover the attributes using TypedArray
<some.text.view.that.i.defined.TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
font:sanFrancisco="bold|italic"/>
<attr name="fontSanFrancisco">
<flag name="regular" value="0"/>
<flag name="bold" value="1"/>
<flag name="italic" value="2"/>
</attr>
<declare-styleable name="font">
<attr name="sanFrancisco" format="flag"/>
</declare-styleable>
The recycle() causes the allocated memory to be returned to the available pool immediately and will not stay until garbage collection. This method is also available for Bitmap .
An <attr> element has two xml attributes name and format . name lets you call it something and this is how you end up referring to it in code, e.g., R. attr. my_attribute . The format attribute can have different values depending on the 'type' of attribute you want.
1. for using custom attributes we need to make File named attr in the values folder of the resource. 2. define your custom attributes in <declare-styleable> tag.
attrs.xml
<resources>
<declare-styleable name="font">
<attr name="my_sampleFlag" />
</declare-styleable>
<attr name="my_sampleFlag">
<flag name="regular" value="0" />
<flag name="bold" value="1" />
<flag name="italic" value="2" />
</attr>
</resources>
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:custom="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:gravity="center">
<com.example.checkstack.MyView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
android:text="Hello World"
android:layout_marginTop="20dip"/>
</LinearLayout>
MyView
public class MyView extends TextView {
public MyView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public MyView(Context context, AttributeSet attrs) {
super(context, attrs);
applyCustomFont(context, attrs);
}
public MyView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
applyCustomFont(context, attrs);
}
private void applyCustomFont(Context context, AttributeSet attrs) {
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.font);
int textStyle = a.getInt(R.styleable.font_my_sampleFlag, 1);
setTypeface(null, textStyle);
a.recycle();
}
}
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