カスタムコンテナビューを作成することは絶対に可能であり、推奨されています。これは、Androidが複合コントロールと呼ぶものです。だから、:
public class MyCustomView extends RelativeLayout {
private LinearLayout mContentView;
public MyCustomView(Context context) {
this(context, null);
}
public MyCustomView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public MyCustomView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
//Inflate and attach your child XML
LayoutInflater.from(context).inflate(R.layout.custom_layout, this);
//Get a reference to the layout where you want children to be placed
mContentView = (LinearLayout) findViewById(R.id.content);
//Do any more custom init you would like to access children and do setup
}
@Override
public void addView(View child, int index, ViewGroup.LayoutParams params) {
if(mContentView == null){
super.addView(child, index, params);
} else {
//Forward these calls to the content view
mContentView.addView(child, index, params);
}
}
}
あなたが必要ですが、最終的に彼らはすべて私がサンプルに配置されたバージョンにコールバックを感じるようあなたがaddView()
のように多くのバージョンを上書きすることができます。このメソッドをオーバーライドすると、フレームワークはXMLタグ内のすべての子を特定の子コンテナに渡します。その後、
、そのようにXMLを変更します。
のres /レイアウト/ custom_layout.xml
<merge>
<SomeView />
<SomeOtherView />
<!-- maybe more layout stuff here later -->
<LinearLayout
android:id="@+id/content" />
</merge>
<merge>
を使用する理由は、階層構造を簡素化することです。すべての子ビューは、カスタムクラス(RelativeLayout
)にアタッチされます。 <merge>
を使用しないと、すべての子に添付されたRelativeLayout
が別のRelativeLayout
に添付されてしまい、問題が発生する可能性があります。私は(ないカスタムビューで)他の場所で子どもたちを定義したいと言ったので
あなたが使用できるHTH
ないソリューションが含まれます。より正確には、私はレイアウトファイルa.xml、b.xml、c.xmlを持っています。これらはすべて、同じカスタムビューを使用していますが、LinearLayoutの異なる子を使用しています。 – mreichelt
これも完全に受け入れられます。私が説明したように、最も簡単な方法は 'addView()'をオーバーライドすることです。私は上記の例を編集しました。 – Devunwired
ありがとうございました!このような長い時間が経過してもこれらの問題が解決されることを知りました! :) – mreichelt