有没有办法将自定义的 XML 属性传递给扩展了 View 类的类?

22 浏览
0 Comments

有没有办法将自定义的 XML 属性传递给扩展了 View 类的类?

这个问题已经有答案了:

使用XML声明自定义Android UI元素

假设我有这样一个东西:

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

在xml中我这样使用它:


有没有一种方法可以在MyExcellentView中访问myCustomAttribute

admin 更改状态以发布 2023年5月21日
0
0 Comments

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

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中声明属性:



   
      
   

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


希望这能帮到你。

祝好!

0