How to create a Spinner dynamically in android?
I used the HelloTabWidget from here (http://developer.android.com/resources/tutorials/views/hello-tabwidget.html) as a starting point.
Now I edited the onCreate for the first Tab:
// Initialize a TabSpec for each tab and add it to the TabHost
spec = tabHost.newTabSpec("tab0").setIndicator("Tab0", res.getDrawable(R.drawable.ic_tab_artists));
spec.setContent(new MyTabContentFactory(this, R.layout.tab0));
tabHost.addTab(spec);
MyTabContentFactory:
public class MyTabContentFactory implements TabContentFactory {
private Activity parent = null;
private int layout = -1;
public MyTabContentFactory(Activity parent, int layout) {
this.parent = parent;
this.layout = layout;
}
@Override
public View createTabContent(String tag) {
View inflatedView = View.inflate(parent, layout, null);//using parent.getApplicationContext() threw a android.view.WindowManager$BadTokenException when clicking ob the Spinner.
//initialize spinner
CharSequence array[] = new CharSequence[4];
for (int i = 0; i < array.length; i++) {
array[i] = "Element "+i;
}
ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(parent, android.R.layout.simple_spinner_item, array);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dr开发者_如何学编程opdown_item);
View view = parent.findViewById(layout);
if(view != null) {
ArrayList<View> touchables = view.getTouchables();
for (View b : touchables) {
if (b instanceof Spinner) {
((Spinner) b).setAdapter(adapter);
}
}
}
return inflatedView;
}
}
tab0.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<Spinner
android:id="@+id/entry1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:prompt="@string/brand_prompt"
/>
</RelativeLayout>
MyTabContentFactory should initialize the Spinner, but view in createTabContent is always null. Why is that so? How can I find the Spinner in order to initialize it?
This line
View view = parent.findViewById(layout);
means nothing, I see what your trying to do, but it just doesn't work like that. You can't get views off your activity you have to reference the inflated XML view.
I think what your trying to do is this:
ArrayList<View> touchables = inflatedView.getTouchables();
for (View b : touchables) {
if (b instanceof Spinner) {
((Spinner) b).setAdapter(adapter);
}
}
but tbh you don't even need to do that, you should do this:
Spinner spinner = (Spinner) inflatedView.findViewById(R.id.entry1);
spinner.setAdapter(adapter);
精彩评论