0

我有一个Views包含 a ImageView、 aButton和 a的块TextView。我想在Java代码中动态创建这个块。有没有办法在 XML 中定义这个块,改变src/text属性并将其附加到我的当前layout

谢谢!

罗恩

4

1 回答 1

1

我使用以下技术:

<!-- content.xml -->
<merge>
  <ImageView android:id="@+id/image />
  <Button android:id="@+id/button />
  <TextView android:id="@+id/text />
</merge>

然后使用 a 充气LayoutInflater

View block = inflater.inflate(R.layout.content, root, attach);
(TextView) textView = (TextView) block.findViewById(R.id.text);
textView.setText(text);

当您编写自定义View扩展 a ViewGroup(例如LinearLayoutor 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)
    );
  }
}

A possible variation is using a Layout instead of <merge> if you don't need it. The LayoutInflater can be obtained by Activity.getLayoutInflater() or by any Context via getSystemService() (you have to cast the result to a LayoutInflater object in the latter case.

于 2012-10-25T11:28:40.900 回答