0
public class MyActivity extends Activity {
    Context context;
    List<String> tasks;
    ArrayAdapter<String> adapter;

    /**
     * Called when the activity is first created.
     */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

        context = this;
        tasks = new ArrayList<String>();

        Button add = (Button) findViewById(R.id.button);
        add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                EditText editText = (EditText) findViewById(R.id.editText);
                editText.setVisibility(1);

                InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
                imm.showSoftInput(editText, 0);

                String value = editText.getText().toString();
                tasks.add(value);

                adapter = new ArrayAdapter<String>(context,R.id.listView,tasks);
                ListView listView = (ListView) findViewById(R.id.listView);
                listView.setAdapter(adapter);
            }
        });
    }
}

在这里,我从用户那里获得了价值。我正在尝试将其动态添加到列表视图中。但是,它显示了一个名为“不幸的是应用程序已关闭”的错误。将字符串值添加到任务变量时失败。任务是一个字符串列表。

tasks.add(value);

如果我尝试添加其他内容,它也会失败。喜欢,

tasks.add("something");

我不知道是什么问题。但我确信它在这一行中失败了,因为如果我删除这一行,我的应用程序运行正常。如果有人知道它为什么失败,请告诉我。提前致谢。

4

1 回答 1

5

你的源代码有太多错误。试试下面的代码,了解你在写什么,而不是盲目地复制粘贴。

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

    context = this;
    tasks = new ArrayList<String>();

    // instances all your variables on initial only
    Button add = (Button) findViewById(R.id.button);
    final EditText editText = (EditText) findViewById(R.id.editText);

    // second parameter is row layout, 
    adapter = new ArrayAdapter<String>(context,android.R.layout.simple_list_item1,tasks);
    ListView listView = (ListView) findViewById(R.id.listView);
    listView.setAdapter(adapter);



    add.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {

            editText.setVisibility(1);

            InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
            imm.showSoftInput(editText, 0);

            String value = editText.getText().toString();
            tasks.add(value);

            // this method will refresh your listview manually 
            adapter.notifyDataSetChanged();
        }
    });
}
于 2013-09-24T17:05:16.973 回答