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?

4

1 回答 1

3

是的,这就是你这样做的方式:

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();
}

但是您还必须在 attrs.xml 中声明资源中的属性:

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

此外,为了使用它,您必须这样做:

<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"/>

希望这可以帮助。

问候!

于 2013-09-05T22:51:26.257 回答