如果你看看我的代码。我希望在 ListActivity 中按下按钮时显示警报,在本例中为位置 0。当按下按钮时,我希望显示允许用户创建新类别的警报。我需要获取用户想要的字符串作为类别并将其添加到数组列表中。请帮助我已经尝试了几个小时T_T
public class Data extends ListActivity {
ArrayList<String> items = new ArrayList<String>();
private Context show;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
items.add("+ Create New");
setListAdapter(new ArrayAdapter<String>(Data.this,
android.R.layout.simple_list_item_1, items));
}
@Override
protected void onListItemClick(ListView l, View v, int position, long id) {
// TODO Auto-generated method stub
super.onListItemClick(l, v, position, id);
if (position == 0) {
items.add(getText());
}
protected void getText() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
// Need to add value to arraylist!
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
}
}
……
我想到了。
protected void setCategory() {
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("New Category");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
//create a button that says ok, and can be pressed
public void onClick(DialogInterface dialog, int whichButton) {
Editable value = input.getText();
getValue(value);
//getValue() allows the string to be taken out of this method
items.add(output);//put the string into the global variable
/*
* I dont understand why this way works over making "value" a string and then adding it
* as the global variable.
*/
}
});
alert.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
//do nothing
}
});
alert.show();
}
protected void getValue(Editable theInput) {
String input = theInput.toString();
output = input;
}
}