创建接受其他布局的自定义视图的xml属性视图

3

我在这里有一个待解决的问题,我可能已经找到了一个可能不那么容易出错的解决方案;然而,我不知道如何编写这个解决方案的代码。

这个解决方案非常类似于android.support.design.widget.NavigationView如何处理XML中的头部视图!唯一的问题是,我尝试搜索NavigationView的源代码,但我似乎找不到它。我可以轻松找到其他Android源代码 - 除了较新的Design库。

如果我能从Google找到源代码,那么我就可以实现类似的东西。

代码

<android.support.design.widget.NavigationView
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="start"
        app:menu="@menu/drawer"
        app:headerLayout="@layout/drawer_header"  />

看到最后一行了吗?我想为我的自定义视图做类似的事情,在其中插入另一个视图。
所以我的问题是:
1. 设计库NavigationView的源代码在哪里? 或者 2. 是否有其他允许您在其中插入布局的自定义视图,其代码已发布在线? 或者 3. 如果没有在线内容,那么一个人该如何去做呢?这是可能的。NavigationView就是这样做的。

你可以拥有一个自定义属性,并在你的自定义视图的构造函数中进行部分设置。 - Blackbelt
是的,我知道它将是一个自定义属性。但是一旦它通过属性传递到构造函数中,我不知道该怎么做。 - Christopher Rucinski
不要寻找自定义视图,而是寻找自定义ViewGroup。从我头脑中想到的是一个fab-toolbar库,它接受多个视图并将它们排列在线性布局中。 - Sahil Dave
1
你只需要用该ID填充视图即可。 - Blackbelt
好的,很高兴听起来非常简单。我会继续我的想法,就像我在另一个问题中提到的那样,并按照您的建议去做,因为我现在知道我想要的实际上是可行的。 - Christopher Rucinski
1个回答

6

以下是一个如何实现的示例:
在你的resources.xml文件中:

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

在您的 MyCustomView.java 中:
public class MyCustomView extends ViewGroup {

    public MyCustomView(Context context, AttributeSet attrs) {
        super(context, attrs);

        TypedArray a = context.getTheme().obtainStyledAttributes(attrs, R.styleable.MyCustomView, 0, 0);

        int childView = a.getResourceId(R.styleable.MyCustomView_child_view, R.layout.default_child_view);
        a.recycle();

        LayoutInflater.from(context).inflate(childView, this, true);
    }
}

在你的布局文件中:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              xmlns:custom_view="http://schemas.android.com/apk/res-auto"
              android:layout_width="match_parent"
              android:layout_height="match_parent">

<your.package.MyCustomView
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        custom_view:child_view="@layout/some_layout" />

</LinearLayout>

似乎必须从ViewGroup开始。inflate的第二个参数不起作用。那么这意味着我必须重写OnLayout方法。 - Christopher Rucinski
1
它可以是ViewGroup的间接子类 - 例如,您也可以扩展LinearLayout - Mikhail
我明白了,但如果您查看我的相关问题,您会看到我的XML文件。这样膨胀视图是正确的吗?现在我有一个ViewStub,我想让这个视图进去。 - Christopher Rucinski
@Christopher 等等,你想把视图作为子视图添加到你的 CustomView 中吗? - Mikhail
那是我的原始想法,但链接的方式不一定要这样做。我认为这个问题中的想法足以提供具有正确布局的XML属性。 - Christopher Rucinski
显示剩余3条评论

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接