0

我有一个LinearLayoutViews里面。然后我想将此元素视为View,因此我创建了一个新的class扩展 from LinearLayout。现在,当我在布局中动态添加一个新instance的时,我什么也看不到。class我相信我必须以View某种方式从我的 中获取class,但不知道如何。是否有可能以某种方式将这个新类与 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
4

1 回答 1

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.
}

现在你可以像这样在你的 xmls 中使用它:

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

包括:

很简单,使用include标签:

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

以下是 RomainGuy 的布局技巧

于 2012-12-22T13:54:45.177 回答