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

Chr*_*ski 3 android view android-custom-view android-layout

我在这里有一个悬而未决的问题,我正在尝试解决,并且我可能已经找到了一个不太容易出错的可能解决方案;但是,我不知道如何编写解决方案。

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

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

代码

<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"  />
Run Code Online (Sandbox Code Playgroud)

看到最后一行了吗?我希望能够为我自己的 customView 执行类似的操作,以在其中插入另一个视图。

所以我的问题是:

  • 设计库的NavigationView的源代码在哪里?

    或者

  • 是否有另一个自定义视图允许您在其中插入已在线发布代码的布局?

    或者

  • 如果网上什么都没有,那么一个人将如何去做呢?有可能的。导航视图可以做到这一点。

Mik*_*ail 6

这是您可以如何做到这一点的示例:
在您的resources.xml

<declare-styleable name="MyCustomView">
   <attr name="child_view" format="reference" />
</declare-styleable>
Run Code Online (Sandbox Code Playgroud)

在你的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);
    }
}
Run Code Online (Sandbox Code Playgroud)

在您的布局文件中:

<?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>
Run Code Online (Sandbox Code Playgroud)