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

时间:2015-07-17 11:36:01

标签: android android-layout view android-custom-view

我在这里有一个open question,我试图解决,我可能找到了一个不太容易出错的解决方案;但是,我不知道如何编写解决方案。

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

如果我能从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"  />

看到最后一行?我希望能够为我自己的customView做类似的事情,在其中插入另一个视图。

所以我的问题是:

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

    或者

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

    或者

  • 如果网上什么都没有,那么一个人怎么会这样做呢?有可能的。 NavigationView就是这样做的。

1 个答案:

答案 0 :(得分:4)

以下是您可能会这样做的例子:
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>