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



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

解决方案将非常类似于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"  />
看到最后一行了吗?我希望我自己的customView也能像那样在里面插入另一个视图

所以我的问题是:

  • 哪里是设计库的导航视图的源代码?

  • 是否有另一个自定义视图,允许您插入布局里面的代码张贴在网上?

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

下面是一个示例:
在你的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>

最新更新