如果你看看我的代码。我希望在ListActivity中按下按钮时显示警报,在这种情况下位置0.当按下它时,我想要显示警报,允许用户创建新类别。我需要获取用户想要的字符串作为类别并将其添加到arraylist。请帮助我尝试了几个小时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;
}
}
答案 0 :(得分:0)
private ArrayAdapter<String> adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
items.add("+ Create New");
adapter = new ArrayAdapter<String>(Data.this,
android.R.layout.simple_list_item_1, items)
setListAdapter(adapter);
}
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String inputText = input.getText().toString()
adapter.add(inputText);
/* if need add to items
items.add(inputText);
*/
}
});