0
我用這裏的HelloTabWidget(http://developer.android.com/resources/tutorials/views/hello-tabwidget.html)作爲起點。如何在android中動態創建一個Spinner?
現在我編輯的onCreate第一個選項卡:
// 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_dropdown_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應該初始化微調,但查看createTabContent始終爲空。爲什麼?我如何找到Spinner來初始化它?
感謝。我明天會嘗試。 順便說一句。你的第二種方法對我不起作用。我不知道視圖中有多少Spinners。 – Burkhard
它適用於這個例子。 – Blundell
它的工作原理。謝謝! – Burkhard