单击应用程序崩溃的列表视图的微调框元素(android)

时间:2014-11-02 19:29:23

标签: java android android-layout android-listview android-spinner

所以我是android / java编程的初学者,我试着做以下事情:当我点击按钮时,我的微调器中的选定项应该进入列表视图。到目前为止,我做到了这一点,eclipse没有显示任何错误或警告,但是当我尝试启动它时,我的应用程序崩溃了:

public class MainActivity extends ActionBarActivity {


    Button button3;
    Button button2;
    Button button4;
    ListView listView1;
    Spinner s1;
    String text;

    ArrayAdapter<String> adapter;
    ArrayList<String> list;
    int itemPos;

     @Override
        protected void onCreate(Bundle savedInstanceState) {

            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);

            button3 = (Button) findViewById(R.id.button3); 
            button4 = (Button) findViewById(R.id.button4); 
            button2 = (Button) findViewById(R.id.button2);
            s1 = (Spinner) findViewById(R.id.spinner1);
            listView1 = (ListView) findViewById(R.id.listView1);



            adapter = new ArrayAdapter<String>(this,
                    android.R.layout.simple_list_item_single_choice, list);  //this part here might not be correct
                listView1.setAdapter(adapter);

                button3.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View v) {

                        String text = s1.getSelectedItem().toString();
                        adapter.add(text);    
                    }});


     listView1.setOnItemClickListener(new OnItemClickListener() {
      @Override
      public void onItemClick(AdapterView<?> parent, View view,
        int position, long id) {

        itemPos = position;

      }
    });}}

我不明白为什么会崩溃,如何解决?

谢谢你!

1 个答案:

答案 0 :(得分:0)

申报,

ArrayList<String> list = new ArrayList<String>();

现在,您不能直接在ArrayAdapter中发送文本,因为我们已经创建了ArrayList。

所以这样做,

    button3.setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {

            String text = s1.getSelectedItem().toString();
            list.add(text);
            // To notify adapter after that changes in data 
            adapter.notifyDataSetChanged();
        }
    });

如果问题是这样的话。