0

、 、およびViewsを含むブロックがあります。このブロックをコード内で動的に作成したいと考えています。このブロックを XML で定義し、/属性を変更して、現在の に追加する方法はありますか?ImageViewButtonTextViewJavasrctextlayout

ありがとう!

ロン

4

1 に答える 1

1

私は次のテクニックを使用します。

<!-- 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()ContextgetSystemService()LayoutInflater

于 2012-10-25T11:28:40.900 に答える