I am trying to retrieve a value for a custom attribute I have defined for a Fragment. My issue is that the returned value for the custom attribute when accessed by TypedArray.getInteger() is always 0 instead of the value that was set in the layout file - but only on devices running 5.0.
To reference a few resources I have found to be helpful in trying to solve my problem: Google's FragmentArgument demo for obtaining custom styled attributes, this stackoverflow post which has been referenced on a few other stackoverflow questions regarding obtaining custom attributes for Android Fragments, and this article.
Using these resources, I have successfully obtained custom attributes set for a fragment on devices running api 16 - 19, but not on devices running Android L.
Code snippets:
res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="ComposerFragment">
<attr name="position" format="enum">
<enum name="left" value="1"/>
<enum name="right" value="2"/>
</attr>
</declare-styleable>
</resources>
composer_activity.xml (layout file)
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent"
>
<!-- other views elided -->
<fragment
android:name="com.mypackage.name.ui.fragment.ComposerFragment"
android:id="@+id/left_composer"
<!-- layout attributes elided -->
app:position="left">
<requestFocus/>
</fragment>
<fragment
android:name="com.mypackage.name.ui.fragment.ComposerFragment"
android:id="@+id/right_composer"
<!-- layout attributes elided -->
app:position="right"
/>
</RelativeLayout>
ComposerFragment.java (extends support Fragment)
@Override
public void onInflate(Activity activity, AttributeSet attrs, Bundle savedInstanceState) {
super.onInflate(activity, attrs, savedInstanceState);
TypedArray a = activity.obtainStyledAttributes(attrs, R.styleable.ComposerFragment);
mBackgroundScrollerPosition =
a.getInteger(R.styleable.ComposerFragment_position, Position.NOT_SPECIFIED); // Position.NOT_SPECIFIED == 0
a.recycle();
}
I have tried <attr name="position" format="integer">
in attrs.xml and just setting app:position="1"
in the layout xml, but the value returned in a.getInteger(R.styleable.ComposerFragment_position, Position.NOT_SPECIFIED);
is always 0 - on devices running 5.0.
As previously stated, my approach works on devices running JellyBean and KitKat.