[英]How to Inflate Extended LinearLayout from XML
任何人都可以建议一种方法来改进这个API8的例子吗? 虽然他们说这些视图可以用XML定义,但他们实际上做的是用java编写代码。 我明白为什么他们想要。 他们已经将一些成员添加到扩展的LinearLayout中,并且这些值是在运行时确定的。
根据哦,宇宙中的每个人,布局指令应该转移到XML。 但是对于这个应用程序,在运行时逻辑中保持原样设置是有意义的。 所以我们有一种混合方法。 膨胀视图,然后填充动态文本。 我无法弄清楚如何完成它。 这是源头和我尝试过的。
private class SpeechView extends LinearLayout {
public SpeechView(Context context, String title, String words) {
super(context);
this.setOrientation(VERTICAL);
// Here we build the child views in code. They could also have
// been specified in an XML file.
mTitle = new TextView(context);
mTitle.setText(title);
...
我想因为LinearLayout有一个android:id =“@ + id / LinearLayout01”,我应该能够在OnCreate中做到这一点
SpeechView sv = (SpeechView) findViewById(R.id.LinearLayout01);
但它永远不会击中我添加的最小构造函数:
public class SpeechView extends LinearLayout {
public SpeechView(Context context) {
super(context);
System.out.println("Instantiated SpeechView(Context context)");
}
...
我只是碰到了这个确切的问题我自己。 我认为你(我们)需要的是这个,但我仍然在处理一些错误,所以我还不能肯定地说:
public class SpeechView extends LinearLayout {
public SpeechView(Context context) {
super(context);
View.inflate(context, R.layout.main_row, this);
}
...
如果你有运气的话我会很想听。
编辑:现在就像这样为我工作。
看起来你夸大了你的布局,它位于main_row.xml文件中。 正确? 我的需求是不同的。 我想要扩展我在main.xml中的布局的TextView子项。
不过,我使用了类似的解决方案。 因为我已经在onCreate中从XML中膨胀了LinearLayout
setContentView(R.layout.main);
剩下的就是在我的View构造函数中从XML中扩展TextView。 这就是我做到的。
LayoutInflater li = LayoutInflater.from(context);
LinearLayout ll = (LinearLayout) li.inflate(R.layout.main, this);
TextView mTitle = (TextView) ll.findViewById(R.id.roleHeading);
R.id.roleHeading是我正在膨胀的TextView的id。
<TextView android:id="@+id/roleHeading" ... />
为了提高效率,我能够将LayoutInflater移动到Activity成员,以便它只被实例化一次。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.