How do I use obtainStyledAttributes(int []) with internal Themes of Android - android

So I have looked around and found out that android.R.styleable is no longer part of the SDK even though it is still documented here.
That wouldn't really be an issue if it was clearly documented what the alternative is. For example the AOSP Calendar App is still using the android.R.styleable
// Get the dim amount from the theme
TypedArray a = obtainStyledAttributes(com.android.internal.R.styleable.Theme);
lp.dimAmount = a.getFloat(android.R.styleable.Theme_backgroundDimAmount, 0.5f);
a.recycle();
So how would one get the backgroundDimAmount without getting the int[] from android.R.styleable.Theme?
What do I have to stick into obtainStyledAttributes(int []) in order to make it work with the SDK?

The CustomView API demo shows how to retrieve styled attributes. The code for the view is here:
https://github.com/android/platform_development/blob/master/samples/ApiDemos/src/com/example/android/apis/view/LabelView.java
The styleable array used to retrieve the text, color, and size is defined in the <declare-styleable> section here:
https://github.com/android/platform_development/blob/master/samples/ApiDemos/res/values/attrs.xml#L24
You can use <declare-styleable> to define any list of attributes that you want to retrieve as a group, containing both your own and ones defined by the platform.
As far as these things being in the documentation, there is a lot of java doc around the styleable arrays that makes them useful to have in the documentation, so they have been left there. However as the arrays change, such as new attributes being added, the values of the constants can change, so the platform ones can not be in the SDK (and please do not use any tricks to try to access them). There should be no need to use the platform ones anyway, because they are each there just for the implementation of parts of the framework, and it is trivial to create your own as shown here.

In the example, they left out the reference to the Context 'c':
public ImageAdapter(Context c) {
TypedArray a = c.obtainStyledAttributes(R.styleable.GalleryPrototype);
mGalleryItemBackground = a.getResourceId(
R.styleable.GalleryPrototype_android_galleryItemBackground, 0);
a.recycle();
return mGalleryItemBackground;
}
Changing obtainStyledAttributes to c.obtainStyledAttributes should work

Example of pulling out standard attribute (background) in a custom view which has its own default style. In this example the custom view PasswordGrid extends GridLayout. I specified a style for PasswordGrid which sets a background image using the standard android attribute android:background.
public class PasswordGrid extends GridLayout {
public PasswordGrid(Context context) {
super(context);
init(context, null, 0);
}
public PasswordGrid(Context context, AttributeSet attrs) {
super(context, attrs, R.attr.passwordGridStyle);
init(context, attrs, 0);
}
public PasswordGrid(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init(context, attrs, defStyle);
}
private void init(Context context, AttributeSet attrs, int defStyle) {
if (!isInEditMode()) {
TypedArray stdAttrs = context.obtainStyledAttributes(attrs,
new int[] { android.R.attr.background }, // attribute[s] to access
defStyle,
R.style.PasswordGridStyle); // Style to access
// or use any style available in the android.R.style file, such as
// android.R.style.Theme_Holo_Light
if (stdAttrs != null) {
Drawable bgDrawable = stdAttrs.getDrawable(0);
if (bgDrawable != null)
this.setBackground(bgDrawable);
stdAttrs.recycle();
}
}
}
Here is part of my styles.xml file:
<declare-styleable name="passwordGrid">
<attr name="drawOn" format="color|reference" />
<attr name="drawOff" format="color|reference" />
<attr name="pathWidth" format="integer" />
<attr name="pathAlpha" format="integer" />
<attr name="pathColor" format="color" />
</declare-styleable>
<style name="PasswordGridStyle" parent="#android:style/Widget.GridView" >
<!-- Style custom attributes. -->
<item name="drawOff">#drawable/ic_more</item>
<item name="drawOn">#drawable/ic_menu_cut</item>
<item name="pathWidth">31</item>
<item name="pathAlpha">129</item>
<item name="pathColor">#color/green</item>
<!-- Style standard attributes -->
<item name="android:background">#drawable/pattern_bg</item>
</style>

This appears to be a bug in the SDK. I have filed an issue on it, which you may wish to star so as to receive updates on it.
As a worksaround, you can use reflection to access the field:
Class clazz=Class.forName("android.R$styleable");
int i=clazz.getField("Theme_backgroundDimAmount").getInt(clazz);

Related

How to pass custom attributes to nested xml

I have structure like that:
preferences.xml:
...
<com.example.MyCustomPreference
...
myCustomMessage="#string/abc"
android:inputType="..."
... />
...
preference_my_custom.xml:
<LinearLayout ...>
<com.example.MyCustomView
...
app:myCustomMessage="?????"
... />
</LinearLayout>
view_my_custom.xml:
<GridView ...>
...EditTexts, TextViews, etc.
</GridView>
I would like to pass myCustomMessage's value (I omitted other attributes for simplification) from MyCustomPreference to MyCustomView using XML. MyCustomView reads custom attributes, so I would like to avoid reading attributes in MyCustomPreference programmatically, getting TextViews from MyCustomView and setting them values. However, I really don't know what to type in place of "?????".
How can i do this using XML? Is this possible?
You have to do it programmatically (unless you use data binding). For example, in your MyCustomPreference you catch de attribute myCustomMessage:
String myCustomMessage = null;
TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomPreference, 0, 0);
try {
myCustomMessage = a.getString(R.styleable.MyCustomPreference_myCustomMessage);
} finally {
a.recycle();
}
Here you got the String value of your attribute. Then, I supose you have inflated your MyCustomView inside your MyCustomPreference. As an example:
View.inflate(getContext(), R.layout.preference_my_custom, this);
MyCustomView myCustomView = (MyCustomView) findViewById(R.id.you_custom_view_id);
So, here you can set programmatically your myCustomMessage in your MyCustomView.
myCustomView.setMyCustomMessage(myCustomMessage);
You should create this method to set correctly your text, and if necessary propagate this text to other child views of your MyCustomView.
Now, changing your String resId in your preferences.xml the interface should update as expected.
P.S: Since I don't know all your resource ids, please adapt them to your project.
Create an attribute file for your customeView:
Add in attrs.xml
<declare-styleable name="CustomView">
<attr name="width" format="dimension" />
</declare-styleable>
Used in your customView init:
public CustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.CustomView, defStyle, 0);
mWidth = a.getDimensionPixelSize(R.styleable.CustomView_width,0);
a.recycle();
}

Library's style attributes have no values even though they are explicitly set

I made a library with a custom view that inflates a layout when created. Views in the layout are styled with style="?attr/labelStyle" or any other attribute.
The attribute is declared the library's attrs.xml:
<attr name="myViewStyle" format="reference"/>
<declare-styleable name="MyView">
<attr name="labelStyle" format="reference|color"/>
</declare-styleable>
I have set a default value to this attribute in the library's styles.xml:
<style name="MyViewStyle">
<item name="labelStyle">#style/LabelStyle</item>
</style>
<style name="LabelStyle">
<item name="android:textColor">?android:attr/textColorPrimary</item>
<item name="...">...</item>
</style>
And finally in the library's themes.xml:
<style name="MyViewStyleLight" parent="Theme.AppCompat.Light">
<item name="myViewStyle">#style/MyViewStyle</item>
</style>
Now this was the library's default styles, but it is overridden in the main project styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="myViewStyle">#style/MyViewStyleCustom</item>
</style>
<style name="MyViewStyleCustom" parent="MyViewStyleLight">
<item name="android:textColor">#color/gray</item>
<item name="...">...</item>
</style>
The custom view code:
public MyView(Context context) {
this(context, null, R.attr.myViewStyle, 0);
}
public MyView(Context context, #Nullable AttributeSet attrs) {
this(context, attrs, R.attr.myViewStyle, 0);
}
public MyView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, 0);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(createThemeWrapper(context, R.attr.myViewStyle, R.style.MyViewStyleLight),
attrs, defStyleAttr, defStyleRes);
initLayout();
}
private static Context createThemeWrapper(Context context, int styleAttr, int defaultStyle) {
final TypedArray ta = context.obtainStyledAttributes(new int[]{styleAttr});
int style = ta.getResourceId(0, defaultStyle);
ta.recycle();
return new ContextThemeWrapper(context, style);
}
private void initLayout() {
LayoutInflater inflater = LayoutInflater.from(getContext());
inflater.inflate(R.layout.my_view, this);
...
}
I explain about the ContextThemeWrapper below. Now the app crashes on the line where the layout gets inflated. Here's the important part of the crash log:
android.view.InflateException: Binary XML file line #0: Binary XML file line #0: Error inflating class com.example.MyView
at android.view.LayoutInflater.inflate(LayoutInflater.java:539)
at android.view.LayoutInflater.inflate(LayoutInflater.java:423)
[...]
Caused by: java.lang.UnsupportedOperationException: Failed to resolve attribute at index 13: TypedValue{t=0x2/d=0x7f030057 a=-1}
at android.content.res.TypedArray.getDrawable(TypedArray.java:867)
[...]
The layout inflater can't find the attribute's value. When I tried to get the attribute by code, it returns nothing. The attribute actually exists, only it has no value set to it even though I have clearly set one.
How exactly I am supposed to style my library? I am almost certain that I did every thing the same as the SublimePicker library but it just won't work. There's a little difference in the part with the ContextThemeWrapper, but it probably isn't the problem. I feel like I forgot a tiny thing somewhere that makes the attribute have no value, something is not connected, I don't know.
I know this is a very long question, but it cannot be more concise, I simplified everything as much as I could. I changed most of the information that was in the previous version of my question, making it completely different. The two answers are not relevant at all now, not that they ever were. The bounty was automatically rewarded.
If that could help someone I can add a download to my actual project, but as I said this simplified example has the exact same form as my project.
This answer is based on what I understand from your question and conversation between you and Vinayak B. If I misinterpret ,Please correct me.
there is difference in style.xml in both place app as well as lib. addition I have removed theme.xml as well as changes in constructor of MyView.java for default style
I have changed following things
overridden in the main project styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light">
<item name="myViewStyle">#style/MyViewStyleCustom</item>
</style>
<style name="MyViewStyleCustom" parent="MyViewStyle">
<item name="labelStyle">#style/LabelStyle123</item>
</style>
<style name="LabelStyle123">
<item name="android:textColor">#f00</item>
</style>
lib styles.xml
<resources>
<style name="MyViewStyle">
<item name="labelStyle">#style/LabelStyle</item>
<item name="TextStyle">#style/textStyle</item>
</style>
<style name="LabelStyle">
<item name="android:textColor">#00f</item>
</style>
<style name="textStyle">
<item name="android:textColor">#009</item>
</style>
</resources>
MyView.java - changed constructor of and set default MyViewStyle if no any attribute come from application.
public MyView(Context context) {
this(context, null, R.attr.myViewStyle, R.style.MyViewStyle);
}
public MyView(Context context, #Nullable AttributeSet attrs) {
this(context, attrs, R.attr.myViewStyle, R.style.MyViewStyle);
}
public MyView(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
this(context, attrs, defStyleAttr, R.style.MyViewStyle);
}
public MyView(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
super(createThemeWrapper(context, defStyleAttr,defStyleRes), attrs, defStyleAttr, defStyleRes);
initLayout();
}
private static Context createThemeWrapper(Context context, int styleAttr, int defaultStyle) {
final TypedArray ta = context.obtainStyledAttributes(new int[]{styleAttr});
int style1 = ta.getResourceId(0, defaultStyle);
ta.recycle();
return new ContextThemeWrapper(context, style1);
}
so either it will take default labelStyle if it is not overridden in main activity style or overridden labelStyle
This answer is based on what I understand from your question. If I misinterpret
,Please correct me.
First of all myTextColor is an attribute name in your library. not a attribute value. You supposed to give a value for myTextColor when ever you using this library. Otherwise there may occur 'InflateException' . You can avoid this by following way.
<YourCustomeView
android:layout_width="match_parent"
android:layout_height="match_parent"
app:myTextColor="#000"/>
1. Set myTextColor value directly when you use outside the library.
OR
In your library where you using this myTextColor attribute, check if this attribute have value or not. If it doesn't have any value then use a default value for myTextColor
private void init(#Nullable AttributeSet attrs) {
TypedArray ta = getContext().obtainStyledAttributes(attrs,
R.styleable.MyLibrary);
boolean hasRawRes = ta.hasValue(R.styleable.myTextColor);
if(hasRawRes){
// Use `myTextColor` attr here
}else{
// use default color
}
}
UPDATE ANSWER
This answer for the updated question
First of all you are trying to fetch a attr value from your library to your project using ?attr/ .Which does not going to work. because
Your project using Theme.AppCompat theme as (I'm guessing) parent theme for your Activities. When you use ?attr inside that activity, you can only fetch attribute values of Theme.AppCompat. But you are trying to fetch ?attr/labelStyle which is not a attribute of Theme.AppCompat rather than it's your library attribute. That's why you are getting that crash. If you want to use any style from your library to your project you can use #style tag
For example
style="#style/labelStyle"
If it's not what you are looking for ,Please kindly share your source code.So I can understand more on this problem.
Here's my guess: I suspect that, despite <style> tag you posted above, the attribute is actually not defined when inflating from your library, probably because your library project is using a Context with a "bad" theme when inflating the dialog.
The ?attr syntax means that the value for the variable is read from the context's theme, not from a view's style or attributes. From a Google dev blog post:
This ?attr/ format allows you to pull any attribute out of your theme, making it easy to consolidate your theming into a single place and avoid finding/replacing across many files.
So you have to make sure that you either handle the case where the inflating context's theme does not define this attribute, or only ever inflate this dialog with a theme that defines the attribute.

Working with styleable

I wanted to make a view containing a progress view and a button. Through the view's xml I wanted to add fields that define button and porgress bar style.
What I've done so far but it does not work:
<io.**.**.view.ButtonLoading android:id="#+id/b_recover_password"
android:layout_width="wrap_content"
android:gravity="center"
app:styleButton="#style/ButtonGrey"
app:styleProgress="#style/ProgressBar"
app:textButton="#string/recover_password"
android:layout_height="wrap_content"/>
Code:
a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.ButtonLoading,
0, 0);
int buttonId = 0;// R.style.Widget_AppCompat_Button;
try {
buttonId = a.getResourceId(R.styleable.ButtonLoading_styleButton, 0);
} catch (Exception e) {
}
button = new Button(getContext(), attrs, buttonId);
LayoutParams lpButton = createLayoutParams();
button.setLayoutParams(lpButton);
color = button.getCurrentTextColor();
int progressId = 0;// R.style.Widget_AppCompat_ProgressBar;
try {
progressId = a.getResourceId(R.styleable.ButtonLoading_styleProgress, 0);
} catch (Exception e) {
}
progressBar = new ProgressBar(getContext(), attrs, progressId);
LayoutParams lpProgressBar = createLayoutParams();
lpProgressBar.addRule(RelativeLayout.CENTER_IN_PARENT);
progressBar.setLayoutParams(lpProgressBar);
LayoutParams lpRelativeLayout = createLayoutParams();
setLayoutParams(lpRelativeLayout);
addView(button);
addView(progressBar);
try {
String value = a.getString(R.styleable.ButtonLoading_textButton);
button.setText(value);
} catch (Exception e) {
}
a.recycle();
Styleable:
<declare-styleable name="ButtonLoading">
<attr name="styleButton" format="reference" />
<attr name="styleProgress" format="reference" />
<attr name="textButton" format="string" />
</declare-styleable>
Someone help me? thanks
The problem is in your constructors for Button and ProgressBar. Let's consider two of the constructors. (Emphasis is mine.) (Documentation)
View(Context context, AttributeSet attrs, int defStyleAttr) [Appropriate for below API 21]
Perform inflation from XML and apply a class-specific base style from a theme attribute. This constructor of View allows subclasses to use their own base style when they are inflating. For example, a Button class's constructor would call this version of the super class constructor and supply R.attr.buttonStyle for defStyleAttr; this allows the theme's button style to modify all of the base view attributes (in particular its background) as well as the Button class's attributes.
View(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) [Appropriate for API 21+]
Perform inflation from XML and apply a class-specific base style from a theme attribute or style resource. This constructor of View allows subclasses to use their own base style when they are inflating.
Focusing on the last two arguments.
defStyleAttr int: An attribute in the current theme that contains a reference to a style resource that supplies default values for the view. Can be 0 to not look for defaults.
defStyleRes int: A resource identifier of a style resource that supplies default values for the view, used only if defStyleAttr is 0 or can not be found in the theme. Can be 0 to not look for defaults.
It is confusing because there are resource ids pointing to resource ids, but bear with me.
What you have defined for buttonId and progressId is a resource id that points to a style (<style...). This style resource id is appropriate to use for the defStyleRes attribute of the Button and ProgressBar constructors as noted .above. You are trying to use each of these resource values as an id that points to an attribute in the current theme. In other words, you are saying that R.attr.styleButton (styleButton) is an attribute in the current theme which it is not as currently defined. To fix this, change the theme style to the following:
styles.xml
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<item name="styleButton">#style/ButtonGrey</item>
...
</style>
To make what you have work with API 21+ you can leave the leave the style and layout files as they are and change the custom view code to something like the following. (I am only showing code for the button, but the progress bar would be similar.) You may want to create a separate style file for API 21+ (styles-v21.xml).
public CustomViewGroup(Context context, #Nullable AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
TypedArray a = context.getTheme().obtainStyledAttributes(
attrs,
R.styleable.ButtonLoading,
0, 0);
int defStyleRes = 0;
try {
defStyleRes = a.getResourceId(R.styleable.ButtonLoading_styleButton, 0);
} catch (Exception e) {
// do something
}
Button button;
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
// defStyleRes is only used if defStyleAttr == 0
// or can't be found in the current theme.
button = new Button(getContext(), attrs, defStyleAttr, defStyleRes);
} else {
button = new Button(getContext(), attrs,
(defStyleAttr != 0) ? defStyleAttr : R.attr.styleButton);
}
try {
String value = a.getString(R.styleable.ButtonLoading_textButton);
button.setText(value);
} catch (Exception e) {
// do something
}
addView(button);
a.recycle();
}
Setting the text of the button proceeds as you have coded. Styles are trickier. To makeapp:styleButton="#style/ButtonGrey" work as you intended for all APIs, I think that you would have to do something like this.
I hope this helps.
The my styles is:
<!-- Base application theme. -->
<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
<!-- Customize your theme here. -->
<item name="colorPrimary">#color/colorPrimary</item>
<item name="colorPrimaryDark">#color/colorPrimaryDark</item>
<item name="colorAccent">#color/colorAccent</item>
<item name="android:buttonStyle">#style/ButtonAppTheme</item>
<item name="android:progressBarStyle">#style/ProgressBarBase</item>
</style>
<style name="ProgressBarBase" parent="android:Widget.Holo.Light.ProgressBar">
<item name="android:textColorTertiary">#color/color_grey</item>
</style>
<style name="ProgressBar" parent="android:Widget.Holo.Light.ProgressBar">
<item name="android:textColorTertiary">#color/color_black</item>
</style>
The problem is that you always have the "ProgressBarBase" style. That is, it is not overriding.

Problem copying AbsoluteLayout - com.android.internal.R cannot be resolved

I came to a problem that the only solutions is using a AbsoluteLayout (Just to show something at specific positions).
I'm trying to copy the AbsoluteLayout class to avoid it being removed on future releases and my app stop working.
I'm copying from here: http://www.google.com/codesearch#cZwlSNS7aEw/frameworks/base/core/java/android/widget/AbsoluteLayout.java&exact_package=android&q=AbsoluteLayout&type=cs
But getting this code, first, I changed all the mPadding(Direction) to getPadding(Direction), but there's still an error on the LayoutParams constructor:
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs,
com.android.internal.R.styleable.AbsoluteLayout_Layout);
x = a.getDimensionPixelOffset(
com.android.internal.R.styleable.AbsoluteLayout_Layout_layout_x, 0);
y = a.getDimensionPixelOffset(
com.android.internal.R.styleable.AbsoluteLayout_Layout_layout_y, 0);
a.recycle();
}
com.android.internal.R cannot be resolved to a variable
How can I get these values? Or someone already has this class independently that don't belong to google wishes to keep on the API?
You need to copy over declare-styleable entry from attrs.xml:
<declare-styleable name="AbsoluteLayout_Layout">
<attr name="layout_x" format="dimension" />
<attr name="layout_y" format="dimension" />
</declare-styleable>
Just add res/values/attrs.xml file to your application and copy above lines there.
When this is done, update your code to reference R from your package:
import com.your.package.R;
...
public LayoutParams(Context c, AttributeSet attrs) {
super(c, attrs);
TypedArray a = c.obtainStyledAttributes(attrs,
R.styleable.AbsoluteLayout_Layout);
x = a.getDimensionPixelOffset(
R.styleable.AbsoluteLayout_Layout_layout_x, 0);
y = a.getDimensionPixelOffset(
R.styleable.AbsoluteLayout_Layout_layout_y, 0);
a.recycle();
}

Defining custom attrs

I need to implement my own attributes like in com.android.R.attr
Found nothing in official documentation so I need information about how to define these attrs and how to use them from my code.
Currently the best documentation is the source. You can take a look at it here (attrs.xml).
You can define attributes in the top <resources> element or inside of a <declare-styleable> element. If I'm going to use an attr in more than one place I put it in the root element. Note, all attributes share the same global namespace. That means that even if you create a new attribute inside of a <declare-styleable> element it can be used outside of it and you cannot create another attribute with the same name of a different type.
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.
reference - if it references another resource id (e.g, "#color/my_color", "#layout/my_layout")
color
boolean
dimension
float
integer
string
fraction
enum - normally implicitly defined
flag - normally implicitly defined
You can set the format to multiple types by using |, e.g., format="reference|color".
enum attributes can be defined as follows:
<attr name="my_enum_attr">
<enum name="value1" value="1" />
<enum name="value2" value="2" />
</attr>
flag attributes are similar except the values need to be defined so they can be bit ored together:
<attr name="my_flag_attr">
<flag name="fuzzy" value="0x01" />
<flag name="cold" value="0x02" />
</attr>
In addition to attributes there is the <declare-styleable> element. This allows you to define attributes a custom view can use. You do this by specifying an <attr> element, if it was previously defined you do not specify the format. If you wish to reuse an android attr, for example, android:gravity, then you can do that in the name, as follows.
An example of a custom view <declare-styleable>:
<declare-styleable name="MyCustomView">
<attr name="my_custom_attribute" />
<attr name="android:gravity" />
</declare-styleable>
When defining your custom attributes in XML on your custom view you need to do a few things. First you must declare a namespace to find your attributes. You do this on the root layout element. Normally there is only xmlns:android="http://schemas.android.com/apk/res/android". You must now also add xmlns:whatever="http://schemas.android.com/apk/res-auto".
Example:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:whatever="http://schemas.android.com/apk/res-auto"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<org.example.mypackage.MyCustomView
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="center"
whatever:my_custom_attribute="Hello, world!" />
</LinearLayout>
Finally, to access that custom attribute you normally do so in the constructor of your custom view as follows.
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable.MyCustomView, defStyle, 0);
String str = a.getString(R.styleable.MyCustomView_my_custom_attribute);
//do something with str
a.recycle();
}
The end. :)
Qberticus's answer is good, but one useful detail is missing. If you are implementing these in a library replace:
xmlns:whatever="http://schemas.android.com/apk/res/org.example.mypackage"
with:
xmlns:whatever="http://schemas.android.com/apk/res-auto"
Otherwise the application that uses the library will have runtime errors.
The answer above covers everything in great detail, apart from a couple of things.
First, if there are no styles, then the (Context context, AttributeSet attrs) method signature will be used to instantiate the preference. In this case just use context.obtainStyledAttributes(attrs, R.styleable.MyCustomView) to get the TypedArray.
Secondly it does not cover how to deal with plaurals resources (quantity strings). These cannot be dealt with using TypedArray. Here is a code snippet from my SeekBarPreference that sets the summary of the preference formatting its value according to the value of the preference. If the xml for the preference sets android:summary to a text string or a string resouce the value of the preference is formatted into the string (it should have %d in it, to pick up the value). If android:summary is set to a plaurals resource, then that is used to format the result.
// Use your own name space if not using an android resource.
final static private String ANDROID_NS =
"http://schemas.android.com/apk/res/android";
private int pluralResource;
private Resources resources;
private String summary;
public SeekBarPreference(Context context, AttributeSet attrs) {
// ...
TypedArray attributes = context.obtainStyledAttributes(
attrs, R.styleable.SeekBarPreference);
pluralResource = attrs.getAttributeResourceValue(ANDROID_NS, "summary", 0);
if (pluralResource != 0) {
if (! resources.getResourceTypeName(pluralResource).equals("plurals")) {
pluralResource = 0;
}
}
if (pluralResource == 0) {
summary = attributes.getString(
R.styleable.SeekBarPreference_android_summary);
}
attributes.recycle();
}
#Override
public CharSequence getSummary() {
int value = getPersistedInt(defaultValue);
if (pluralResource != 0) {
return resources.getQuantityString(pluralResource, value, value);
}
return (summary == null) ? null : String.format(summary, value);
}
This is just given as an example, however, if you want are tempted to set the summary on the preference screen, then you need to call notifyChanged() in the preference's onDialogClosed method.
The traditional approach is full of boilerplate code and clumsy resource handling. That's why I made the Spyglass framework. To demonstrate how it works, here's an example showing how to make a custom view that displays a String title.
Step 1: Create a custom view class.
public class CustomView extends FrameLayout {
private TextView titleView;
public CustomView(Context context) {
super(context);
init(null, 0, 0);
}
public CustomView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs, 0, 0);
}
public CustomView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs, defStyleAttr, 0);
}
#RequiresApi(21)
public CustomView(
Context context,
AttributeSet attrs,
int defStyleAttr,
int defStyleRes) {
super(context, attrs, defStyleAttr, defStyleRes);
init(attrs, defStyleAttr, defStyleRes);
}
public void setTitle(String title) {
titleView.setText(title);
}
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
}
}
Step 2: Define a string attribute in the values/attrs.xml resource file:
<resources>
<declare-styleable name="CustomView">
<attr name="title" format="string"/>
</declare-styleable>
</resources>
Step 3: Apply the #StringHandler annotation to the setTitle method to tell the Spyglass framework to route the attribute value to this method when the view is inflated.
#HandlesString(attributeId = R.styleable.CustomView_title)
public void setTitle(String title) {
titleView.setText(title);
}
Now that your class has a Spyglass annotation, the Spyglass framework will detect it at compile-time and automatically generate the CustomView_SpyglassCompanion class.
Step 4: Use the generated class in the custom view's init method:
private void init(AttributeSet attrs, int defStyleAttr, int defStyleRes) {
inflate(getContext(), R.layout.custom_view, this);
titleView = findViewById(R.id.title_view);
CustomView_SpyglassCompanion
.builder()
.withTarget(this)
.withContext(getContext())
.withAttributeSet(attrs)
.withDefaultStyleAttribute(defStyleAttr)
.withDefaultStyleResource(defStyleRes)
.build()
.callTargetMethodsNow();
}
That's it. Now when you instantiate the class from XML, the Spyglass companion interprets the attributes and makes the required method call. For example, if we inflate the following layout then setTitle will be called with "Hello, World!" as the argument.
<FrameLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:width="match_parent"
android:height="match_parent">
<com.example.CustomView
android:width="match_parent"
android:height="match_parent"
app:title="Hello, World!"/>
</FrameLayout>
The framework isn't limited to string resources has lots of different annotations for handling other resource types. It also has annotations for defining default values and for passing in placeholder values if your methods have multiple parameters.
Have a look at the Github repo for more information and examples.
if you omit the format attribute from the attr element, you can use it to reference a class from XML layouts.
example from attrs.xml.
Android Studio understands that the class is being referenced from XML
i.e.
Refactor > Rename works
Find Usages works
and so on...
don't specify a format attribute in .../src/main/res/values/attrs.xml
<?xml version="1.0" encoding="utf-8"?>
<resources>
<declare-styleable name="MyCustomView">
....
<attr name="give_me_a_class"/>
....
</declare-styleable>
</resources>
use it in some layout file .../src/main/res/layout/activity__main_menu.xml
<?xml version="1.0" encoding="utf-8"?>
<SomeLayout
xmlns:app="http://schemas.android.com/apk/res-auto">
<!-- make sure to use $ dollar signs for nested classes -->
<MyCustomView
app:give_me_a_class="class.type.name.Outer$Nested/>
<MyCustomView
app:give_me_a_class="class.type.name.AnotherClass/>
</SomeLayout>
parse the class in your view initialization code .../src/main/java/.../MyCustomView.kt
class MyCustomView(
context:Context,
attrs:AttributeSet)
:View(context,attrs)
{
// parse XML attributes
....
private val giveMeAClass:SomeCustomInterface
init
{
context.theme.obtainStyledAttributes(attrs,R.styleable.ColorPreference,0,0).apply()
{
try
{
// very important to use the class loader from the passed-in context
giveMeAClass = context::class.java.classLoader!!
.loadClass(getString(R.styleable.MyCustomView_give_me_a_class))
.newInstance() // instantiate using 0-args constructor
.let {it as SomeCustomInterface}
}
finally
{
recycle()
}
}
}
HERE is the official documentation for creating custom attributes and Views

Categories

Resources