首先,您必須向Activitymain.xml中添加一個(gè)ListView、一個(gè)EditText和一個(gè)按鈕。
現(xiàn)在,在你的活動(dòng)主題:
private EditText editTxt;private Button btn;private ListView list;private ArrayAdapter<String> adapter;private ArrayList<String>
arrayList;@Overrideprotected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
editTxt = (EditText) findViewById(R.id.editText);
btn = (Button) findViewById(R.id.button);
list = (ListView) findViewById(R.id.listView);
arrayList = new ArrayList<String>();
// Adapter: You need three parameters 'the context, id of the layout (it will be where the data is shown),
// and the array that contains the data
adapter = new ArrayAdapter<String>(getApplicationContext(), android.R.layout.simple_spinner_item, arrayList);
// Here, you set the data in your ListView
list.setAdapter(adapter);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
// this line adds the data of your EditText and puts in your array
arrayList.add(editTxt.getText().toString());
// next thing you have to do is check if your adapter has changed
adapter.notifyDataSetChanged();
}
});}
這對(duì)我有用,我希望我能幫你