1

Assuming I have something that looks like this:

public class MyExcellentView extends View{
  //etc. etc.

}

and in the xml I use it thusly:

<com.my.package.MyExcellentView
 android:layout_width="wrap_content"
 android:layout_height="wrap_content"
 myCustomAttribute="100"
/>

Is there a way to get access to myCustomAttribute within MyExcellentView?

Yevgeny Simkin
  • 26,055
  • 37
  • 127
  • 228

1 Answers1

3

Yes, this is the way you do it:

public MyExcellentView(Context context, AttributeSet attrs){
TypedArray a = context.obtainStyledAttributes(attrs, R.styleable. MyCustomView);
            int customAtt = a.getInteger(R.styleable. MyCustomView_yourCustomAttribute, defaultValue);
            a.recycle();
}

But you also have to declare the attribute in the resources like so in attrs.xml:

<?xml version="1.0" encoding="utf-8"?>
<resources>
   <declare-styleable name="MyCustomView">
      <attr name="yourCustomAttribute"/>
   </declare-styleable>
</resources>

Also in order to use it you have to do it like this:

<com.my.package.MyExcellentView
  xmlns:customAtts="http://schemas.android.com/apk/res/com.my.package"
  android:layout_width="wrap_content"
  android:layout_height="wrap_content"
  customAtts:myCustomAttribute="100"/>

Hope this helps.

Regards!

Martin Cazares
  • 13,001
  • 10
  • 43
  • 54