我有一个应用程序,我想在其中调用一个打开带有数字输入的对话框的方法,我的问题是每当在edittext中插入一个值并按下正按钮时它返回null,然后首先下次通话的价值。
通过调试我发现它创建了元素,然后在跳过我的赋值语句之后返回。
如何防止它过早返回?
private String numbers;
private String getWeight(){
final EditText edittext = new EditText(this);
edittext.setInputType(InputType.TYPE_CLASS_PHONE);
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("How much do you weigh?");
builder1.setView(edittext);
builder1.setCancelable(true);
builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
numbers = edittext.getText().toString();
dialog.cancel();
}
});
builder1.setNeutralButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
numbers = edittext.getText().toString();
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
return numbers;
}
答案 0 :(得分:0)
因此在键入时将editText内容放在String中。
String content;
editText.addTextChangedListener(new TextWatcher() {
@Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
content = s.toString();
}
@Override
public void beforeTextChanged(CharSequence s, int start, int count,int after) {
// TODO Auto-generated method stub
}
@Override
public void afterTextChanged(Editable s) {
if(TextUtils.isEmpty(s)) {
// call method
}
}
});
和setPositiveButton在这里获取内容字符串。
答案 1 :(得分:0)
我有同样的问题并使用以下方法修复它。
您应该为视图创建静态xml布局。不要以编程方式构建它。
更新您的代码
private String numbers;
private String getWeight(){
LayoutInflater inflater = LayoutInflater.from(mContext);
View mView = inflater.inflate(R.layout.weight_simple_input, null);
builder.setView(mView);
AlertDialog.Builder builder1 = new AlertDialog.Builder(this);
builder1.setMessage("How much do you weigh?");
builder1.setView(mView);
builder1.setCancelable(true);
builder1.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
numbers = ((EditText) mView.findViewById(R.id.phone)).getText().toString();
dialog.cancel();
}
});
builder1.setNeutralButton(
"Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
numbers = edittext.getText().toString();
dialog.cancel();
}
});
AlertDialog alert11 = builder1.create();
alert11.show();
}
虽然您已在班级范围内定义了数字,但您无需再次返回。在任何你想要的地方使用它。
最后这里是layout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:layout_height="match_parent">
<EditText
android:layout_width="wrap_content"
android:layout_gravity="center"
android:layout_marginBottom="@dimen/text_margin"
android:layout_height="wrap_content"
android:inputType="numberDecimal"
android:ems="10"
android:id="@+id/weight" />
</LinearLayout>