android显示toast消息
我正在尝试对警告对话框的edittext进行简单验证,如果用户没有在警告对话框的编辑文本中输入他的名字并按下是按钮,则应显示一个toast消息"请输入你的姓名"。
我制作了一个代码来进行此验证,但是在显示警告对话框的吐司消息后问题已关闭,我希望警报对话框仍然打开,直到用户输入他的名字。
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("user info");
alert.setMessage("enter your name");
// Set an EditText view to get user input
final EditText ed = new EditText(context);
int maxLength = 10;
ed.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
maxLength) });
alert.setView(ed);
alert.setCancelable(false);
alert.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
if (ed.getText().toString().length() == 0 )
{
CharSequence error = "please enter your name";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}
else{
startNextActivity(context);
}
}
});
alert.show();
}
答案 0 :(得分:0)
if (ed.getText().length() == 0) {
ed.setError("please enter your name");
} else {
startNextActivity(context);
}
答案 1 :(得分:0)
试试这个,
final AlertDialog d = new AlertDialog.Builder(context)
.setView(v)
.setTitle(R.string.my_title)
.setPositiveButton(android.R.string.ok, null) //Set to null. We override the onclick
.setNegativeButton(android.R.string.cancel, null)
.create();
d.setOnShowListener(new DialogInterface.OnShowListener() {
@Override
public void onShow(DialogInterface dialog) {
Button b = d.getButton(AlertDialog.BUTTON_POSITIVE);
b.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
if (ed.getText().toString().length() == 0 )
{
CharSequence error = "please enter your name";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}else
{
d.dismiss();
}
}
});
}
});
它肯定会起作用,如果确实如此,则标记为正确。 :)
答案 2 :(得分:0)
这对我有用。您必须创建并显示警报对话框,并在需要时将其关闭。所以在此之前对话框显示。
AlertDialog.Builder alert = new AlertDialog.Builder(context);
alert.setTitle("user info");
alert.setMessage("enter your name");
final EditText ed = new EditText(context);
int maxLength = 10;
ed.setFilters(new InputFilter[] { new InputFilter.LengthFilter(
maxLength) });
alert.setView(ed);
alert.setCancelable(false);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
// TODO Auto-generated method stub
}
});
final AlertDialog dialog = alert.create();
dialog.show();
dialog.getButton(AlertDialog.BUTTON_POSITIVE).setOnClickListener(new View.OnClickListener()
{
@Override
public void onClick(View v)
{
if (ed.getText().toString().length() == 0 ){
CharSequence error = "please enter your name";
int duration = Toast.LENGTH_LONG;
Toast toast = Toast.makeText(context, error, duration);
toast.show();
}else{
dialog.dismiss();
}
}
});