2011-06-28 44 views
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來初始化它?

回答

1

此行

View view = parent.findViewById(layout); 

沒什麼意思,我看到你的努力做的,但它只是不喜歡的工作。您不能從您的活動中獲得視圖,您必須引用充值的XML視圖。

我想你想要做的是這樣的:

ArrayList<View> touchables = inflatedView.getTouchables(); 
     for (View b : touchables) { 
      if (b instanceof Spinner) { 
       ((Spinner) b).setAdapter(adapter); 
      } 
     } 

但TBH你甚至都不需要做的是,你應該這樣做:

Spinner spinner = (Spinner) inflatedView.findViewById(R.id.entry1); 
spinner.setAdapter(adapter); 
+0

感謝。我明天會嘗試。 順便說一句。你的第二種方法對我不起作用。我不知道視圖中有多少Spinners。 – Burkhard

+0

它適用於這個例子。 – Blundell

+0

它的工作原理。謝謝! – Burkhard