2013-04-18 217 views
0

我还没有在互联网上找到答案一段时间,现在我问你是否可以帮助我。android,将XML布局视图添加到自定义类中的充气视图

简称: 我应该如何重写addView()(或别的东西)添加在XML定义我的意见“自定义视图充气XML布局”

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

但现在,我想在自定义视图内添加一些内容,但不想在程序中添加它(这很简单),但是使用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的和按键是:使用子类

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文件添加到子类......当然......但在那之后,我从Slider,TextView,Button和我从R.layout.layout_r的膨胀布局中得到了3个孩子。但我只想要1个孩子(layout_r),其中包含Button和TextView。

正如你可以在addView中看到的,我试图简单地将传递的“View child”添加到_innerLayout。那不起作用。 Android框架不断给你打电话addView并与结尾的StackOverflowError

两件事要告诉你太:

  1. 我知道添加的XML浏览犯规致电给addView,但我已经重写所有其他人也和所有看起来是一样的,所以他们不需要展示他们。

  2. 调试说我,那addView被称为前_innerLayout得到膨胀的布局

为2的原因是什么?

你能帮助我吗?

回答

0

充气这个布局中的自定义视图构造方法仅覆盖您addView()方法在您的自定义视图Slider并检查孩子的数量。 如果getChildCount() == 0,那么这是第一次加法,它是视图初始化。

科特林例如:

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