Как динамически создать Spinner в Android? - PullRequest
0 голосов
/ 28 июня 2011

Я использовал отсюда 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 Ответ

1 голос
/ 28 июня 2011

Эта строка

 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);
...