简体   繁体   中英

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?

It looks like something is not right here:

    <RelativeLayout 
        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:farayan="http://schemas.android.com/apk/lib/net.farayan.android.view"

What about change to:

        xmlns:android="http://schemas.android.com/apk/res/android"
        xmlns:farayan="http://schemas.android.com/apk/res/net.farayan.android.view"

net.farayan.android.view is your app root namespace.

update1

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

Here is am example. It use a view defined in the library project.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM