Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypedArray not working

I'm learning about custom components and i'm having some trouble with custom xml attributes.
My custom component extends LinearLayout and in the constructor(public Custom(Context context, AttributeSet attrs))i'm inflating a xml layout(2 Buttons and 1 EditText).
I also declared in values/attrs this custom attributes:

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <declare-styleable name="Custom">
        <attr name="initValue" format="integer" />
        <attr name="stepSize" format="integer" />
        <attr name="maxValue" format="integer"/>
    </declare-styleable>
</resources>


In the constructor after i inflate the layout i'm trying to read the custom attributes like this:

   if (attrs != null) {
                TypedArray ta = context.obtainStyledAttributes(attrs,
                        R.styleable.Custom, 0, 0);
                setInitValue(ta.getInt(R.styleable.Custom_initValue, 0));
                setStepSize(ta.getInt(R.styleable.Custom_stepSize, 1));
                setMaxValue(ta.getInt(R.styleable.Custom_maxValue, 5));         
                ta.recycle();
            }


Now i try to test this custom component by adding it to a xml layout like this:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:orientation="vertical" android:layout_width="fill_parent"
    android:layout_height="fill_parent">
    <here.is.my.package.Custom android:id="@+id/add"
        android:layout_width="wrap_content" android:layout_height="wrap_content"
        initValue="2" maxValue="7" stepSize="1" />
</LinearLayout>


This doesn't work and i get only the default values (0, 1, 5). Am i missing something or this is normal behavior?

like image 837
user Avatar asked Sep 19 '11 14:09

user


2 Answers

Ok, i figured the answer for my question. The answer was that i simply used my custom xml attributes with no namespace and android just ignored them and gave me the default values. After adding my namespace:

   <?xml version="1.0" encoding="utf-8"?>
    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:customAttribute="http://schemas.android.com/apk/res/gere.is.my.package"
        android:orientation="vertical" android:layout_width="fill_parent"
        android:layout_height="fill_parent">
        <here.is.my.package.Custom android:id="@+id/add"
            android:layout_width="wrap_content" android:layout_height="wrap_content"
            customAttribute:initValue="2" customAttribute:maxValue="7" customAttribute:stepSize="1" />
    </LinearLayout>

everything worked.

like image 143
user Avatar answered Nov 17 '22 08:11

user


In Gradle projects, use

xmlns:customView="http://schemas.android.com/apk/res-auto"

this works for me!

like image 35
Shubham Agarwal Avatar answered Nov 17 '22 08:11

Shubham Agarwal