【问题标题】:Custom View with custom xml attribute: How to refeference a layout具有自定义 xml 属性的自定义视图:如何引用布局
【发布时间】:2013-05-29 11:11:42
【问题描述】:

有人知道,如何以编程方式(在代码中)为我的自定义小部件获取引用的 xml 布局。我已经创建了一个自定义的可声明样式,具有我想要的属性,并且我知道如何获取其他 xml 属性值,例如字符串或整数。

我想做的是这样的:

<MyCustomView
    xmlns:my="http://schemas.android.com/apk/res-auto"
    id="@+id/view"
    my:headerLayout="@layout/my_fancy_layout"
    />

所以我想以编程方式检索 my_fancy_layout 并在 MyCustomView 的代码中扩展该布局。

知道怎么做吗?

编辑:我想我可以用

检索资源 ID

int resId = attrs.getAttributeResourceValue(androidns, "headerLayout", 0);

但是,如果我的 MyCustomView 是一个库项目并且我想使用,那么正确的命名空间是什么

xmlns:my="http://schemas.android.com/apk/res-auto"

【问题讨论】:

    标签: android xml android-custom-view


    【解决方案1】:

    您确实可以在自定义视图的构造函数中扩展您的布局:

    public class MyCustomView extends /* LinearLayout, RelativeLayout, etc. */ {
        public MyCustomView(Context context, AttributeSet attrs) {
            super(context, attrs);
            initView(context, attrs);
        }
        public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
            initView(context, attrs);
        }
        protected void initView(Context context, attrs) {
            LayoutInflater.from(context).inflate(attrs.getAttributeResourceValue("http://schemas.android.com/apk/res-auto", "headerLayout", 0), this, true);
        }
    }
    

    【讨论】:

    • 是的,这很清楚,但我想在 xml 中指定布局。所以我想用 xml 中指定的值替换 R.layout.my_custom_view 的值
    【解决方案2】:

    好的,我自己找到了解决方案:

    你必须从你的 AttributeSet 中检索一个 TypedArray。

    您可以通过以下方式访问所需的资源 ID:

    TypedArray attrs = ... ;
    int headerRes = attrs.getResourceId(R.styleable.MyCustomWidget_headerLayout, -1);
    

    你可以像往常一样膨胀:

    LayoutInflater.from(context).inflate(headerRes, this);
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2013-09-01
      • 1970-01-01
      • 2011-03-16
      • 2011-03-07
      • 2012-07-16
      • 2012-07-01
      • 2013-05-05
      相关资源
      最近更新 更多