我是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;
}
}
答案 0 :(得分: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
}
});
答案 1 :(得分:1)
我认为 - 在按钮上单击布局按钮将不可见&amp;列表布局将可见。
doItems.add(item)
& After that myListView.setAdapter(aa);