如何在android中动态创建Spinner?

时间:2011-06-28 19:05:33

标签: android spinner

我从这里使用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应初始化Spinner,但createTabContent中的视图始终为null。为什么会这样?如何找到Spinner以进行初始化?

1 个答案:

答案 0 :(得分:1)

这一行

 View view = parent.findViewById(layout);

没有任何意义,我看到你想要做什么,但它只是不起作用。您无法获得有关活动的视图,您必须引用膨胀的XML视图。

我认为你要做的是:

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

但是你甚至不需要这样做,你应该这样做:

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