【问题标题】:Correct way to fetch attributes for custom views?获取自定义视图属性的正确方法?
【发布时间】:2013-08-02 20:13:17
【问题描述】:

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

【问题讨论】:

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


    【解决方案1】:

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

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

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

    查看文档中的此链接:

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

    祝你好运!

    【讨论】:

      猜你喜欢
      • 2011-01-19
      • 1970-01-01
      • 1970-01-01
      • 2022-01-13
      • 2013-03-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多