2

我是 Android 编程的初学者,希望在用户单击按钮时将用户在 EditText 中输入的文本显示到 ListView 中。我写的代码是:

public class MainActivity extends Activity {

    @Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);     
    ListView myListView = (ListView) findViewById(R.id.myListView);
    final EditText myEditText = (EditText) findViewById(R.id.myEditText);       
    final ArrayList<String> todoItems = new ArrayList<String>();
    final ArrayAdapter<String> aa;
    aa = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, todoItems);
    myListView.setAdapter(aa);      
    Button myButton = (Button) findViewById(R.id.myButton);     
    myButton.setOnClickListener(new View.OnClickListener() {
    String item;
        @Override
        public void onClick(View v) {
            // TODO Auto-generated method stub
            item = myEditText.getText().toString();
            //Toast.makeText(null, item, Toast.LENGTH_SHORT).show();//Problem here

        }
    });
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
    // Inflate the menu; this adds items to the action bar if it is present.
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

}

4

2 回答 2

3

嗨 asp_NewBee,您应该将新输入的 EditText 项目添加到您的列表 todoItems 中,如下面的 onclick 块内。从你的代码

  myButton.setOnClickListener(new View.OnClickListener() {
        String item;
            @Override
            public void onClick(View v) {
                // TODO Auto-generated method stub
                item = myEditText.getText().toString();
                //Toast.makeText(getApplicationContext(), item, Toast.LENGTH_SHORT).show();//Problem here

// Add your input text to list as follows
              todoItems.add(item );  // Now list todoItems has been added with new item at end of list.

       aa.notifyDataSetChanged();   // So your list adapter to be refreshed with new item




            }
        });
于 2012-11-22T06:42:29.520 回答
1

我认为-在按钮上单击按钮的布局将不可见,而列表的布局将可见。

 doItems.add(item)
& After that  myListView.setAdapter(aa);    
于 2012-11-22T06:41:21.240 回答