android - @layout 引用的自定义 xml 属性

标签 android xml android-custom-view

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

<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>

最佳答案

首先,您必须创建自定义字段。你可以通过将下面的代码添加到 res/values/attrs.xml

来做到这一点
<declare-styleable name="MyCustomView">
    <attr name="headerLayout" format="reference" />
</declare-styleable>

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

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

关于android - @layout 引用的自定义 xml 属性,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25303979/

相关文章:

android - adb 找不到 Galaxy S3 Android 4.3

Android onBackStackChanged() 未调用

android - 从 Android 中的形状图案裁剪图像

android - 我如何在具有许多绘图形状的自定义 View 上创建边框

android - 带有文字说明的无限滚动画廊 View

添加 Firebase Analytics 后 Android 应用崩溃

javascript - React Native - 不变违规 : Objects are not valid as a React child

java - ArrayAdapter 要求资源 ID 为 TextView

iphone - 如何将 xml 转换为 sqlite?

java - 用于简单 xml 节点字符串的 Android XML 解析器