如何在android中动态地将字符串添加到ListView?

时间:2013-09-24 16:08:54

标签: android android-layout android-listview

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);
            }
        });
    }
}

在这里,我从用户那里获得了价值。我试图动态地将它添加到列表视图。但是,它显示一个名为“Unfortunatly app is closed”的错误。将字符串值添加到tasks变量是失败的。 tasks是一个字符串列表。

tasks.add(value);

如果我尝试添加别的东西也会失败。等,

tasks.add("something");

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

1 个答案:

答案 0 :(得分: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();
        }
    });
}