当我点击按钮时,我想在ListView中添加元素。我为此搜索太多,但无法解决问题。
如果你想我无法发给你代码,我到底想要什么。
package com.example.listrefreshdemo;
import android.app.Activity;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.EditText;
import android.widget.ListView;
public class MainActivity extends Activity {
private EditText editText;
private Button button;
private String[] myStringArray = null;
ArrayAdapter<String> adapter = null;
ListView listView;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myStringArray = new String[] { "hello", "hi" };
adapter = new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1, myStringArray);
listView = (ListView) findViewById(R.id.listView);
listView.setAdapter(adapter);
editText = (EditText) findViewById(R.id.editText);
button = (Button) findViewById(R.id.button);
button.setOnClickListener(buttonClickListener);
}
private OnClickListener buttonClickListener = new OnClickListener() {
@Override
public void onClick(View v) {
String toAdd = editText.getText().toString().trim();
if (toAdd.length() > 0) {
editText.setText("");
String[] tempArray = new String[myStringArray.length + 1];
int i = 0;
for (i = 0; i < myStringArray.length; i++)
tempArray[i] = myStringArray[i];
tempArray[i] = toAdd;
myStringArray = tempArray;
adapter.notifyDataSetChanged();
}
editText.setText("");
}
};
}