动态创建微调器

时间:2011-08-14 22:49:54

标签: java android spinner

我正在努力动态创建一个微调器。我在页面上有它,但每次我尝试选择一个选项时都会爆炸。我的原始代码位于底部。我通过将addSpinner()函数移到内部类之外并更改

来修复它
Spinner newSpinner = new Spinner(getApplicationContext());

Spinner newSpinner = new Spinner(this);

它是固定的,但我不知道它最初不起作用。谁能解释一下? (道歉,如果这是一个菜鸟问题 - 我是Java和Android的新手)

public class SpotManageActivity extends Activity
{
    private SimpleCursorAdapter mSpots;

    @Override
    protected void onCreate(Bundle savedInstanceState)
    {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.reminder_manage_activity);

        Button add_new_button = (Button) findViewById(R.id.add_new_spot_button);
        add_new_button.setOnClickListener(new ButtonOnClickListener());

    }

    public class ButtonOnClickListener implements View.OnClickListener
    {
        @Override
        public void onClick(View v)
        {
            addSpinner();
        }

        private void addSpinner()
        {
            LinearLayout layoutHolder = 
                (LinearLayout) findViewById(R.id.layout_holder);

            LinearLayout spinnerHolder = new LinearLayout(getApplicationContext());
            spinnerHolder.setOrientation(LinearLayout.HORIZONTAL);

            spinnerHolder.setLayoutParams(
                new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.FILL_PARENT, 
                    LinearLayout.LayoutParams.WRAP_CONTENT, 1f));
            Spinner newSpinner = new Spinner(getApplicationContext());
            newSpinner.setLayoutParams(
                new Spinner.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, 
                    ViewGroup.LayoutParams.WRAP_CONTENT));
            newSpinner.setAdapter(mSpots);

            layoutHolder.addView(spinnerHolder);
            spinnerHolder.addView(newSpinner);

            // A non-internal spot was selected
        }

    }

}

1 个答案:

答案 0 :(得分:2)

我根本不确定,但是如果在堆栈跟踪中你得到一些关于错误上下文的信息,那可能是因为Spinner在点击时会打开一个Dialog,而Dialog需要一个Activity上下文。

欲了解更多信息: