android,将XML布局视图添加到自定义类中的膨胀视图

时间:2013-04-18 14:33:33

标签: android xml layout

我还没有在互联网上找到答案很长一段时间,现在我问你是否可以帮助我。

短: 我应该如何覆盖addView()(或其他东西)以将XML中定义的视图添加到我的“自定义视图膨胀的XML布局”

长: 我想为我的Android应用程序创建一个自定义视图,所以我从RelativeLayout创建了一个干净的子类。在这里,我让Inflater加载一个xml布局以获得一个不错的风格。

但是现在,我想在自定义视图中添加一些内容,但不想以编程方式添加它(这很简单),但是使用xml。我无法跨越差距,找到解决方案......

代码: 自定义类:

public class Slider extends RelativeLayout {

    private RelativeLayout _innerLayout;

    public Slider(Context context) {
        super(context);
        init();
    }

    public Slider(Context context, AttributeSet attrs) {
        super(context, attrs);
        init();
    }

    protected void init() {
        LayoutInflater layoutInflater = (LayoutInflater) this.getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        _innerLayout = (RelativeLayout) layoutInflater.inflate(R.layout.layout_r, this);

    }

    @Override
    public void addView(View child) {
        //if (_innerLayout != null) _innerLayout.addView(child);
        super.addView(child);
    }

... all other addView's are overridden in the same way

使用子类的XML文件:

<packagename....Slider
    android:id="@+id/slider1"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@color/Red" >
        <TextView
            android:id="@+id/heading"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="HEADING" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignParentRight="true"
            android:text="bbb" />

...

TextView和Button被添加到子类......当然......但是之后,我在Slider,TextView,Button和R.layout.layout_r的膨胀布局中有3个孩子。但我只想要一个带有Button和TextView的子节点(layout_r)。

正如您在addView中看到的,我试图简单地将传递的“View child”添加到_innerLayout。那不起作用。 Android框架一直在调用addView,它以StackOverFlowError结束

有两件事要告诉你:

  1. 我知道从XML中添加视图并不会调用给定的addView,但我也会覆盖所有其他视图,所有其他视图都相同,因此无需显示它们。

  2. 调试器说我,在_innerLayout获取膨胀的布局之前调用addView

  3. 原因是什么?

    你帮我吗?

2 个答案:

答案 0 :(得分:1)

您可以了解如何将儿童充气到自定义视图here (vogella tutorial)

您需要的是:

  1. 使用<merge>标记
  2. 为子项定义布局
  3. 使用LayoutInflater.inflate(res, this, true)
  4. 在自定义视图构造函数中展开此布局

答案 1 :(得分:0)

只需覆盖自定义视图addView()中的Slider方法,然后检查子项数。 如果getChildCount() == 0,那么这是第一次添加,它是视图初始化。

Kotlin例子:

override fun addView(child: View?, index: Int, params: ViewGroup.LayoutParams?) {
    if (childCount == 0) {
        super.addView(child, index, params)
    } else {
        // Do my own addition
    }
}
相关问题