【发布时间】:2017-11-05 21:33:28
【问题描述】:
所以这是另一个已经被提出一百万次的问题,但我仍然做错了什么。使用 EditText.getText() 将返回一个空字符串。
我在我制作的一个小型自定义对话框中执行此操作。我正在使用 AlertDialog Builder 构建它,这可能会导致问题?我现在真的不知道。
我尝试过的一些事情/关于我对这个问题的了解:
我正在检查 OK 按钮的单击侦听器中的文本,因此我不会尝试在有值之前获取值,这是我看到的常见错误。
我在我的 XML 中为 EditText 对象设置了 ID,调试器似乎显示我正确地引用了它们。
我尝试在 onCreateDialog 方法之外定义 EditText 对象,但这并没有改变任何事情(尽管我很好奇哪种做法更好)。
-
在 getText() 之前使用 EditText.setText() 将允许它返回 setText() 中使用的参数,但它似乎没有获取用户输入的值。
这是我的自定义对话框片段:
public class GPSLocationDialogFragment extends DialogFragment {
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
LayoutInflater inflater = getActivity().getLayoutInflater();
final View view = inflater.inflate(R.layout.gps_dialog, null);
final EditText latitudeText = (EditText) view.findViewById(R.id.latitude);
final EditText longitudeText = (EditText) view.findViewById(R.id.longitude);
// Define the dialog
builder.setView(inflater.inflate(R.layout.gps_dialog, null))
.setMessage("Manually input a GPS address")
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
Log.d("myTag", "Text: " + latitudeText.getText()); // This prints ""
// These throw errors since they're trying to parse "" as a double
double latitude = Double.parseDouble(latitudeText.getText().toString());
double longitude = Double.parseDouble(longitudeText.getText().toString());
}
})
.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
dialog.cancel();
}
});
// Create the AlertDialog object and return it
return builder.create();
}
}
这是我从我的活动中调用对话框的方式:
GPSLocationDialogFragment gpsDialog = new GPSLocationDialogFragment();
gpsDialog.show(getFragmentManager(), "GPSDialog");
这是我的布局 .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:id="@+id/longitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:hint="@string/longitude"
android:inputType="numberSigned|numberDecimal" />
<EditText
android:id="@+id/latitude"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_marginTop="16dp"
android:layout_marginBottom="4dp"
android:layout_marginLeft="16dp"
android:layout_marginRight="16dp"
android:hint="@string/latitude"
android:inputType="numberSigned|numberDecimal" />
</LinearLayout>
如果需要更多上下文,我可以分享它,我尝试简化为相关代码。
【问题讨论】:
标签: java android android-edittext