有人可以建议一种方法来改进这个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)");
}
...
答案 0 :(得分:11)
我自己遇到了这个确切的问题。我认为你(我们)需要的是这个,但我仍然在处理一些错误,所以我还不能肯定地说:
public class SpeechView extends LinearLayout {
public SpeechView(Context context) {
super(context);
View.inflate(context, R.layout.main_row, this);
}
...
如果你有运气,我会很想知道。
编辑:现在就像这样为我工作。
答案 1 :(得分:3)
看起来你夸大了你的布局,它位于main_row.xml文件中。正确?我的需求是不同的。我想要扩展我在main.xml中的布局的TextView子项。
尽管如此,我还是使用了类似的解决方案。因为我已经在onCreate
中从XML中膨胀了LinearLayoutsetContentView(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成员,以便它只被实例化一次。