2011-06-28 8 views
0

ここからのHelloTabWidget(http://developer.android.com/resources/tutorials/views/hello-tabwidget.html)を出発点として使用しました。 どのように動的にアンドロイドでスピナーを作成するのですか?

は今、私は最初のタブのための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は常にnullです。どうしてこんなことに?それを初期化するために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

感謝。私は明日それを試してみるよ。 BTW。あなたの2番目の方法は私のためには機能しません。私はどのくらいのスピナーが見えているのか分かりません。 – Burkhard

+0

しかし、それは例のために働く。 – Blundell

+0

それは動作します。ありがとう! – Burkhard

関連する問題