【问题标题】:Custom xml attribute to a @layout reference@layout 引用的自定义 xml 属性
【发布时间】:2014-08-14 08:55:11
【问题描述】:

我想用自己的 xml 属性制作一个自定义视图。我想指定一个将在我的自定义 xml 视图中膨胀的标题布局,如下所示:

<com.example.MyCustomWidget
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    app:headerLayout="@layout/my_header"
   />

这可能吗?如何从TypedArray 获取布局资源?

所以最后我想做这样的事情:

class MyCustomWidget extends FrameLayout { 


public ProfileTabLayout(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);

    TypedArray a = getContext().obtainStyledAttributes(attrs, R.styleable.ProfileTabLayout);

    int headerLayout = a.getLayout(R.styleable.MyCustomView_headerLayout, 0); // There is no such method

   a.recycle();

   LayoutInflater.from(context)
        .inflate(headerLayout, this, true);

  }

}


<?xml version="1.0" encoding="utf-8"?>
<resources>
  <declare-styleable name="MyCustomWidget">
    <attr name="headerLayout" format="reference" />
  </declare-styleable>
</resources>

【问题讨论】:

  • 请提及您希望在哪个自定义视图(ListView、TextView、anyLayout)上执行@layout/header....并详细说明您的问题..
  • 也许我的问题不清楚。我已经更新了我的问题并添加了一个代码示例。 @pskink 我知道如何声明自定义 xml 属性。我的问题是,是否可以参考布局资源?
  • 当然,格式是参考

标签: android xml android-custom-view


【解决方案1】:

首先,您必须创建自定义字段。哟通过将下面的代码添加到res/values/attrs.xml 来做到这一点

<declare-styleable name="MyCustomView">
    <attr name="headerLayout" format="reference" />
</declare-styleable>

然后在您的自定义视图中,您可以在构造函数中获取此值

public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
    super(context, attrs, defStyle);
    ...
    TypedArray a = context.getTheme().obtainStyledAttributes(
            attrs,
            R.styleable.MyCustomView,
            defStyle, 0
    );

    try {
        int headerLayout = a.getResourceId(R.styleable.MyCustomView_headerLayout, 0);
    } finally {
        a.recycle();
    }
    ...
}

从这里你可以用LayoutInflater膨胀headerLayout

【讨论】:

  • 啊,a.getResourceId() 是我要找的。谢谢!
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2014-10-24
  • 2013-06-17
  • 2011-12-18
  • 2013-02-20
相关资源
最近更新 更多