0

我正在尝试从我的自定义视图类的 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);
4

1 回答 1

1

Using a TypedArray is preferred as accessing the attributes directly has some disadvantages.

The two disadvantages I could find in the Android Documentation are the follwoing:

  • Resource references within attribute values are not resolved
  • Styles are not applied

Take a look at this link from the documentation:

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

Good Luck!

于 2013-08-02T20:23:38.067 回答