在Android中以编程方式创建微调器 [英] Create a spinner programmatically in Android

查看:50
本文介绍了在Android中以编程方式创建微调器的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想创建一个不使用XML的微调框.我是android的新手,我的知识很有限.到目前为止,我已经有了这段代码(请参见上文),并且希望我的微调器位于TabActivity的选项卡之一中. 没有明显的错误,但是当我打开活动时,该选项卡为空.我会感谢您的帮助.

I want to create a spinner without using XML. I am new in android and my knowledge is limited. By now I have this code (see above) and I want my spinner in one of the tabs of my TabActivity. There is no obvious error but when I open my activity the tab is empty. I would appreciate some help.

public void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    ArrayList<String> spinnerArray = new ArrayList<String>();
    spinnerArray.add("one");
    spinnerArray.add("two");
    spinnerArray.add("three");
    spinnerArray.add("four");
    spinnerArray.add("five");

    Spinner spinner = new Spinner(this);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
    spinner.setAdapter(spinnerArrayAdapter);

}

推荐答案

您需要将Spinner添加到布局中.

You need to add the Spinner to a layout.

首先为Spinner创建一个container,然后创建Spinner并将其添加到您的container中.接下来将Activity的内容设置为container.

First create a container for the Spinner and then create the Spinner and add it to your container. Next set content of you Activity to your container.

可以在您的onCreate方法中这样完成:

This could be done like this, in your onCreate method:

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_my);

    LinearLayout layout = new LinearLayout(this);

    ArrayList<String> spinnerArray = new ArrayList<String>();
    spinnerArray.add("one");
    spinnerArray.add("two");
    spinnerArray.add("three");
    spinnerArray.add("four");
    spinnerArray.add("five");

    Spinner spinner = new Spinner(this);
    ArrayAdapter<String> spinnerArrayAdapter = new ArrayAdapter<String>(this, android.R.layout.simple_spinner_dropdown_item, spinnerArray);
    spinner.setAdapter(spinnerArrayAdapter);

    layout.addView(spinner);

    setContentView(layout);
}

只需澄清一下:如果Spinner没有添加到布局内的Activity的内容中,则它是不可见的,因此这就是为什么您不会得到任何错误或任何东西的原因,因为其中没有本身的代码中没有任何错误;-)

Just to clarify: if the Spinner isn't added to the content of the Activity inside a layout, it isn't visible, so that's why you don't get any errors or anything, because there isn't any errors in your code, per se ;-)

这篇关于在Android中以编程方式创建微调器的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆