我希望用户可以多次更改按钮的文本。为了做到这一点,他在那个按钮上长按了一下。这是代码:
@Override
public void onCreate(Bundle savedInstanceState) {
//blah blah
final AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setMessage("Nueva Categoria:");
// Seting 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) {
Button esteBoton = (Button) findViewById(R.id.button1);
String newCateg = input.getText().toString();
esteBoton.setText(newCateg);
}
});
Button button = (Button) findViewById(R.id.button1);
button.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
alert.show();
return true;
}
});
}
Ok。当我在Eclipse的设备模拟器中运行此代码时,如果这是我第一次在Alert Dialog中为按钮1输入文本,则不会出现问题,但是如果我第二次尝试输入代码,则应用程序会崩溃。我不是Java专家,但我认为这是由于"输入"的"最终"属性,一旦确定,我就不能改变它的值。我该怎么修理它?代码很简单,我想保持这种方式。
尝试删除onCreate中的构建器部分,并将其移动到onLongClickListener
Button button;
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.symptoms);
button = (Button) findViewById(R.id.btDone);
// final Dialog alert = builder.create();
button.setOnLongClickListener(new View.OnLongClickListener() {
public boolean onLongClick(View v) {
// Declare your builder here -
final AlertDialog.Builder builder = new AlertDialog.Builder(
YOURACTIVITY.this);
builder.setMessage("Nueva Categoria:");
// Seting an EditText view to get user input
final EditText input = new EditText(YOURACTIVITY.this);
builder.setView(input);
builder.setPositiveButton("Ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
String newCateg = input.getText().toString();
button.setText(newCateg);
}
});
builder.show();
return true;
}
});
}
试试下面的代码:
public class MainActivity extends Activity { Button button; Context context; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); context = MainActivity.this; setContentView(R.layout.activity_main); button = (Button) findViewById(R.id.button1); button.setOnLongClickListener(new View.OnLongClickListener() { public boolean onLongClick(View v) { final AlertDialog.Builder alert = new AlertDialog.Builder( context); alert.setMessage("Nueva Categoria:"); // Seting an EditText view to get user input final EditText input = new EditText(context); alert.setView(input); alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int whichButton) { String newCateg = input.getText().toString(); button.setText(newCateg); } }); AlertDialog build = alert.create(); build.show(); return true; } }); } }
在按钮的onLongClickListener中定义对话框。看看代码,它现在工作得很棒。