Java Android-动态构建视图块并将其附加到布局中
我有一块Java Android-动态构建视图块并将其附加到布局中,java,android,android-layout,android-view,Java,Android,Android Layout,Android View,我有一块视图,其中包含一个图像视图、一个按钮和一个文本视图。我想在Java代码中动态创建这个块。是否有方法用XML定义此块,更改src/text属性并将其附加到我当前的布局 谢谢 Ron我使用以下技术: <!-- content.xml --> <merge> <ImageView android:id="@+id/image /> <Button android:id="@+id/button /> <TextView andr
视图
,其中包含一个图像视图
、一个按钮
和一个文本视图
。我想在Java
代码中动态创建这个块。是否有方法用XML定义此块,更改src
/text
属性并将其附加到我当前的布局
谢谢
Ron我使用以下技术:
<!-- content.xml -->
<merge>
<ImageView android:id="@+id/image />
<Button android:id="@+id/button />
<TextView android:id="@+id/text />
</merge>
当您编写自定义的视图
扩展视图组
(例如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)
);
}
}
一种可能的变化是使用
布局
,而不是
,如果您不需要它的话。LayoutInflater
可以通过或通过任何上下文
通过(在后一种情况下,您必须将结果强制转换为LayoutInflater
对象。如果我多次使用此块…如何避免通过id寻址视图时遇到问题?id/图像将多次出现,不是吗?id
只是查找视图的标识符。它甚至不需要在层次结构中是唯一的。N当两个视图具有相同ID时不会发生任何情况。唯一的问题是,当调用View.findViewById(int)
时,存在两个或多个具有相同ID的视图,因为在这种情况下,您可能找不到要查找的内容(在某些情况下,您可能需要使用setTag(Object)
)。但是使用我的代码,您不会有任何问题,因为充气器返回上次创建的层次结构,您可以在此层次结构上调用findViewById
,并在content.xml
中调用不重复的IDhm…似乎只附加了一个块…知道为什么吗?
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)
);
}
}