我有一个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
(例如 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
而不是<merge>
如果你不需要它。 LayoutInflater
可以通过 Activity.getLayoutInflater()
获取或通过任何 Context
通过 getSystemService()
(在后一种情况下,您必须将结果转换为 LayoutInflater
对象。
关于java - Android - 动态构建 View block 并将其附加到布局,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13067111/