2012-12-22 16 views
0

我有一个LinearLayout与其中一些Views。然后我想把这个元素当作View,所以我创建了一个新的class,从LinearLayout延伸出来。现在,当我动态地将此class的新instance添加到布局中时,我什么都看不到。我相信我必须从class得到View,但不知道如何。有没有可能以某种方式将这个新类与xml相关联?如何处理一些xml结构作为视图?

更新:

public class Task extends LinearLayout { 

    public Task(Context context) { 
     super(context); 
     LayoutInflater.from(context).inflate(R.layout.task_view, this, false); 
    } 

    public Task(Context context, AttributeSet attrs) { 
     super(context, attrs); 
     LayoutInflater.from(context).inflate(R.layout.task_view, this, false); 

    } 

    public Task(Context context, AttributeSet attrs, int defStyle) { 
     super(context, attrs, defStyle); 
     LayoutInflater.from(context).inflate(R.layout.task_view, this, false); 
    } 
} 

然后:

Task newTask = new Task(getActivity()); 
someLinearLayout.addView((View) newTask); // happens nothing 

回答

0

您可以使用不同的方法,如:

不断膨胀:

public class InflatedView extends LinearLayout 
{ 
     public InflatedView(Context c) 
     { 
      super(c); 
      LayoutInflater.from(this).inflate(R.layout.your_other_layout, this); 
     } 
     //override other constructors too. 
} 

现在你可以在你的个XML使用这样的:

<com.your.package.InflatedView android:layout_height="etc" other:attribute="here" /> 

包括:

很简单,使用包括标签:

<include layout="@layout/your_other_layout"/> 

这里是RomainGuy的layout tricks

+0

仅仅在构造函数中使它膨胀就足够了吗?或者我需要将它返回到某个地方? – Eugene

+0

这就够了,别忘了重写其他2个构造函数。 –

+0

到目前为止还没有工作,我在代码中加入了一些代码,请检查。 – Eugene