我有一个习惯LinearLayout
。在该布局内,我想放置几个小部件。我可以在运行时创建小部件,但宁愿从 XML 加载它们。
我在下面的作品,但我相信它正在创造两个LinearLayouts
,一个在另一个里面。在这个例子中,我想简单地创建Butto
n 并EditText
在CustomLayout
. 使用 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);
}
...
}