Can anyone suggest a way to improve this API8 example? While they say the views could have been defined in XML, what they have in fact done is code them in java. I see why they wanted to. They have added some members to an extended LinearLayout, and the values are determined at runtime.
According to oh, everyone in the universe, the layout directives should move to XML. But for this app, it makes sense to keep setting the text as-is in the runtime logic. So we've got a hybrid approach. Inflate the views, then populate the dynamic text. I'm having trouble figuring out how to accomplish it. Here's the source and what I tried.
from API8 Examples, List4.java
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);
...
I figured since the LinearLayout has an android:id="@+id/LinearLayout01", I should be able to do this in the OnCreate
SpeechView sv = (SpeechView) findViewById(R.id.LinearLayout01);
but it never hits the minimal constructor I added:
public cla开发者_如何学运维ss SpeechView extends LinearLayout {
public SpeechView(Context context) {
super(context);
System.out.println("Instantiated SpeechView(Context context)");
}
...
I just ran into this exact problem myself. What I think you(we) need is this, but I'm still working through some bugs so I can't yet say for sure:
public class SpeechView extends LinearLayout {
public SpeechView(Context context) {
super(context);
View.inflate(context, R.layout.main_row, this);
}
...
I'll be anxious to hear if you have any luck with it.
Edit: It's now working for me just like this.
It looks like you inflated your Layout, which resides in the file main_row.xml. Correct? My need is different. I want to inflate a TextView child of the Layout I have in main.xml.
Still, I used a similar solution. Since I had already inflated the LinearLayout from XML in the onCreate
setContentView(R.layout.main);
what remained is to inflate the TextView from XML in my View constructor. Here's how I did it.
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 is the id of the TextView I'm inflating.
<TextView android:id="@+id/roleHeading" ... />
To increase efficiency I was able to move the LayoutInflater to an Activity member, so that it just gets instantiated once.
精彩评论