Android parsing models for custom widget not working

I created a custom widget for my Android application and I want to create my own styles for it. But when parsing it in a class, it always returns null. Several links went by and could not understand what was the problem? Can anyone help?

My atttr.xml

<resources> <declare-styleable name="Widget"> <attr name="headers" format="reference" /> <attr name="height" format="integer" /> </declare-styleable> </resources> 

Widget class

 public Widget(Context context, AttributeSet attrs) { super(context, attrs); TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.Widget); String[] columns = (String[]) attr .getTextArray(R.styleable.Widget_headers); int height = attr.getInt(R.styleable.Widget_height, 0); } 

And the layout file

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:widget="http://schemas.android.com/apk/lib/com.sample.custom" android:id="@+id/statistics_fragment_layout" android:layout_width="match_parent" android:layout_height="match_parent" android:orientation="vertical" > <com.sample.custom.Widget android:id="@+id/widget" android:layout_width="match_parent" android:layout_height="wrap_content" widget:headers="@array/headers" > </com.sample.custom.Widget> </LinearLayout> 

Arrays.xml

 <resources> <string-array name="headers"> <item>Header1</item> <item>Header2</item> <item>Header3</item> </string-array> </resources> 
+8
java android custom-component
source share
2 answers

After going through a few samples, I realized the problem.

Just replaced the string

 TypedArray attr = context.obtainStyledAttributes(attrs, R.styleable.Widget); 

with this

 TypedArray attr = context.getTheme().obtainStyledAttributes(attrs, R.styleable.Widget,0,0) 
0
source share

Did you try to recycle the array at the end of the view constructor? this link covers most things - creating custom views

+1
source share

All Articles