Search code examples
androidandroid-layoutandroid-viewandroid-custom-view

Create Custom Compound View in Android with Attributes


I have created a custom compound view inside a library application and everything was OK. When I add custom attributes to view, I always get default values. I followed this steps with only one difference: my view is in a library project.

/res/values/attrs.xml

<resources>
    <declare-styleable name="DatePickerView">
        <attr name="showToday" format="boolean" />
        <attr name="calendar" format="enum">
            <enum name="jalali" value="0" />
            <enum name="gregorian" value="1" />
        </attr>
    </declare-styleable>
</resources>

Layout file that contains view:

<RelativeLayout 
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:farayan="http://schemas.android.com/apk/lib/net.farayan.android.view"
...
    <net.farayan.android.view.datepicker.DatePickerView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" 
        farayan:showToday="false"
        farayan:calendar="gregorian"/>
...

Component's code:

int calendar;
boolean showToday;

TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.DatePickerView, 0, 0);
try {
    calendar = a.getInteger(R.styleable.DatePickerView_calendar, 0);
    showToday = a.getBoolean(R.styleable.DatePickerView_showToday, true);
} finally {
    a.recycle();
}

calendar and showToday are always 0 and true respectively. Any idea?


Solution

  • If we add new compound view code and its attributesinside project, we should add this at the beginning of layout:

    xmlns:custom="http://schemas.android.com/apk/res/your_main_app_package
    

    and if new compound view is inside a library project linked to our peoject, we should add this:

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

    Link: https://stackoverflow.com/a/10217752/1152549