【问题标题】:Creating Custom Views that accept other layouts in xml attributes在 xml 属性中创建接受其他布局的自定义视图
【发布时间】:2015-10-07 02:55:10
【问题描述】:

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

解决方案与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 做类似的事情,以便在其中插入另一个视图。

所以我的问题是:

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

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

  • 如果网上什么都没有,那一个人怎么做呢?有可能的。 NavigationView 做到了。

【问题讨论】:

  • 你可以有一个自定义属性,并在你的自定义视图的构造函数中分开它
  • 是的,我知道这将是一个自定义属性。但是我不知道一旦它通过属性传递到构造函数中该怎么办
  • 不是搜索自定义视图,而是搜索自定义视图组。在我的脑海中,有一个 fab-toolbar 库,它接受多个视图并以线性布局排列它们。
  • 您只需要使用该 id 来扩充视图
  • 好的,很高兴这听起来很简单。我将继续我在另一个问题中的想法,并按照您的建议做,因为我现在知道我想要的实际上是可行的。

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


【解决方案1】:

这是一个示例:
在你的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,因为我在其中有另一个布局?
  • @Christopher 如果您想直接膨胀到视图 - 是的,它必须是 ViewGroup 的子类(尽管不一定是直接的)。
  • 看来它必须来自 ViewGroup。膨胀的第二个参数不起作用。那么这意味着我必须覆盖 OnLayout
  • 它可以是ViewGroup 的子类 - 例如,您也可以扩展LinearLayout
  • 知道了,但是如果您查看我的链接问题,您将看到我的 XML 文件。膨胀视图是否正确。现在我有一个 ViewStub 我想要这个视图去
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-01-21
  • 2011-03-16
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2012-07-01
相关资源
最近更新 更多