如何在Android Spinner中找到运行时错误?

时间:2015-01-22 05:33:10

标签: android spinner

我是Android新手,下面是Spinner的代码。

我对此代码没有任何错误,但是当我运行它时我的应用程序崩溃了。

如果代码包含Spinner,则会因“不幸App已停止”错误而崩溃。

但如果我删除Spinner,它的效果非常好。

 private Spinner spinner;
 private static final String[]paths = {"item 1", "item 2", "item 3"};
 @Override

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner = (Spinner)findViewById(R.id.spinner1);
    ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_item,paths);

    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener((OnItemSelectedListener) this);

}


public void onItemSelected(AdapterView<?> parent, View v, int position, long id) 
{

    switch (position) 
    {
        case 0:
        //  System.out.println("india");
            // Whatever you want to happen when the first item gets selected
            break;
        case 1:
            // Whatever you want to happen when the second item gets selected
            break;
        case 2:
            // Whatever you want to happen when the thrid item gets selected
            break;
            default:break;
    }
}

}

1 个答案:

答案 0 :(得分:1)

onCreate 代码替换为以下内容:

protected void onCreate(Bundle savedInstanceState) 
{
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    spinner = (Spinner)findViewById(R.id.spinner1);
    ArrayAdapter<String>adapter = new ArrayAdapter<String>(MainActivity.this,
            android.R.layout.simple_spinner_dropdown_item,paths);


    spinner.setAdapter(adapter);
    spinner.setOnItemSelectedListener(MainActivity.this);

}