、 、およびViews
を含むブロックがあります。このブロックをコード内で動的に作成したいと考えています。このブロックを XML で定義し、/属性を変更して、現在の に追加する方法はありますか?ImageView
Button
TextView
Java
src
text
layout
ありがとう!
ロン
、 、およびViews
を含むブロックがあります。このブロックをコード内で動的に作成したいと考えています。このブロックを XML で定義し、/属性を変更して、現在の に追加する方法はありますか?ImageView
Button
TextView
Java
src
text
layout
ありがとう!
ロン
私は次のテクニックを使用します。
<!-- content.xml -->
<merge>
<ImageView android:id="@+id/image />
<Button android:id="@+id/button />
<TextView android:id="@+id/text />
</merge>
次に、次を使用して膨らませLayoutInflater
ます。
View block = inflater.inflate(R.layout.content, root, attach);
(TextView) textView = (TextView) block.findViewById(R.id.text);
textView.setText(text);
View
これは、カスタム拡張 a ViewGroup
(例:LinearLayout
またはRelativeLayout
) を記述し、宣言型 XML でコンテンツを定義する場合に特に便利です。例えば
public class MyWidget extends LinearLayout {
// Invoked by all of the constructors
private void setup() {
Context ctx = getContext();
inflate(ctx, R.layout.content, this);
((TextView) findViewById(R.id.text)).setText(
ctx.getString(R.string.hello_world)
);
}
}
可能なバリエーションは、必要がない場合のLayout
代わりにa を使用することです。<merge>
は、または任意の経由LayoutInflater
で取得できます(後者の場合、結果をオブジェクトにキャストする必要があります。Activity.getLayoutInflater()
Context
getSystemService()
LayoutInflater