0

我有一个习惯LinearLayout。在该布局内,我想放置几个小部件。我可以在运行时创建小部件,但宁愿从 XML 加载它们。

我在下面的作品,但我相信它正在创造两个LinearLayouts,一个在另一个里面。在这个例子中,我想简单地创建Button 并EditTextCustomLayout. 使用 XML,我该怎么做?

这里有更多细节(编辑:在这个例子下面,我已经包含了一个更正的版本):

<com.example.test.MyActivity
  ... />
  <LinearLayout
    ... />
    <com.example.test.CustomLayout  ***** this is the custom linear layout
      android:id="@+id/custom"
      android:orientation="horizontal"
      android:layout_width="fill_parent"
      android:layout_height="wrap_content" />
    <View
      ... other stuff ... />
</com.example.test.MyActivity>

这是 CustomLayout 内容的 XML:

<LinearLayout
  ... />
  <Button
    ... />
  <EditText
    ... />
</LinearLayout>

最后,LinearLayout 的代码:

public class CustomLayout extends LinearLayout
{
  public CustomLayout (Context context, AttributeSet attrs)
  {
    super(context, attrs);
    Activity act = (Activity)context;
    LayoutInflater inflater = act.getLayoutInflater();
    View view = inflater.inflate (R.layout.custom_layout, this, false);
    addView (view);
  }
  ...
}

修正版

<com.example.test.MyActivity
  ... />
  <LinearLayout
   android:id="@+id/outer_layout
   ... />

    ... other stuff ... 
  </LinearLayout>
</com.example.test.MyActivity>

这是 CustomLayout 内容的 XML:

<merge
  ... />
  <Button
    ... />
  <EditText
    ... />
</merge>

实例化 CustomLayout 的代码

public void addCustomLayout()
{
  LinearLayout outerLayout = (LinearLayout) findViewById (R.id.outer_layout);
  CustomLayout customLayout = new CustomLayout (getContext(), null);
  outerLayout.addView (customLayout, 0);
}

最后,CustomLayout 的代码:

public class CustomLayout extends LinearLayout
{
  public CustomLayout (Context context, AttributeSet attrs)
  {
    super(context, attrs);
    Activity act = (Activity)context;
    LayoutInflater inflater = act.getLayoutInflater();
    View view = inflater.inflate (R.layout.custom_layout, this, true);
  }
  ...
}
4

1 回答 1

1

我在下面的工作,但我相信它正在创建两个 LinearLayouts,一个在另一个里面。

实际上,LinearLayoutButtonEditTextCustomLayout. 为避免这种情况,您可以使用merge标签。你会像这样使用它:

<merge
  ... />
  <Button
    ... />
  <EditText
    ... />
</merge>

然后在你的CustomLayout构造函数中:

super(context, attrs);
Activity act = (Activity)context;
LayoutInflater inflater = act.getLayoutInflater();
View view = inflater.inflate (R.layout.custom_layout, this, true); // addView is not needed anymore
于 2012-09-22T07:14:11.770 回答