私はカスタムを持っていますLinearLayout
。そのレイアウトの中に、いくつかのウィジェットを配置したいと思います。実行時にウィジェットを作成することもできますが、XMLからウィジェットをロードしたいと思います。
LinearLayouts
以下にあるものは機能しますが、一方が他方の内側に2つ作成されていると思います。この例では、単純に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);
}
...
}