0

私はカスタムを持っていますLinearLayout。そのレイアウトの中に、いくつかのウィジェットを配置したいと思います。実行時にウィジェットを作成することもできますが、XMLからウィジェットをロードしたいと思います。

LinearLayouts以下にあるものは機能しますが、一方が他方の内側に2つ作成されていると思います。この例では、単純にButtonとを作成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);
  }
  ...
}
4

1 に答える 1

1

以下にあるものは機能しますが、一方が他方の中に2つのLinearLayoutを作成していると思います。

確かに、に(とLinearLayoutを含むxmlレイアウトから)余分なものがあります。これを回避するために、タグを自由に使用できます。次のように使用します。ButtonEditTextCustomLayoutmerge

<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 に答える