正确获取自定义视图属性的方法?

时间:2013-08-02 20:13:17

标签: android android-xml android-custom-view android-resources

我正在尝试从我的自定义视图类的xml布局文件中获取属性,并且似乎有两种方法可以做到这一点....这些方法之一是更好的练习还是类似的东西?

第一个是使用Typed数组访问所有属性

    public VisualNode(Context context, AttributeSet attrs) {
    super(context, attrs);
    // TODO Auto-generated constructor stub

    //getting all the attributes that might be set in an xml file
    TypedArray a = context.getTheme().obtainStyledAttributes(attrs,
                           R.styleable.VisualNode, 0, 0);       

    String text = a.getString(R.styleable.VisualNode_device_name);
    deviceName = new TextView(context);
    deviceName.setText(text);

直接访问资源

    deviceName = new TextView(context);
    deviceName.setText(R.styleable.VisualNode_device_name);

1 个答案:

答案 0 :(得分:1)

首选使用TypedArray,因为直接访问属性有一些缺点。

我在Android文档中可以找到的两个缺点是:

  • 未解析属性值中的资源引用
  • 未应用样式

从文档中查看此链接:

http://developer.android.com/training/custom-views/create-view.html#applyattr

祝你好运!

相关问题