java - Android - 动态构建 View block 并将其附加到布局

标签 java android android-layout android-view

我有一个Views block ,其中包含一个ImageView、一个Button和一个TextView。我想在 Java 代码中动态创建此 block 。有没有办法在 XML 中定义此 block ,更改 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 时特别有用延长 ViewGroup (例如 LinearLayoutRelativeLayout )并且您想要在声明性 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而不是<merge>如果你不需要它。 LayoutInflater可以通过 Activity.getLayoutInflater() 获取或通过任何 Context通过 getSystemService() (在后一种情况下,您必须将结果转换为 LayoutInflater 对象。

关于java - Android - 动态构建 View block 并将其附加到布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13067111/

相关文章:

Android 模拟器不加载应用程序(崩溃报告)

Android Studio 无法在 gradle 上设置 Jackson Parser

android自定义对话框放在中心,背景变暗

android - Google Inbox 如何显示覆盖键盘的 snackbar ?

android - 将 'wrap_content' 或 '-2' 分配给维度

java - pageradapter 中的 getResources 数组 xml

java - 将应用程序移动到 SD 卡时帐户 validator 丢失

java - 类<?扩展 T> 用法

java - 如何在运行时获取设备高度和宽度?

java - 在 JButton 子级中实现 ActionListener