我在AlertDialog中添加了AutocompleteSupportFragment。
AlertDialog
我要确保用户单击“创建”按钮后位置字段不为空。 (就像我确保其他字段不为空一样。)
Fields validation
我希望有一个类似setOnPlaceUnselectedListener的东西。但是AutocompleteSupportFragment仅具有setOnPlaceSelectedListener,这是不理想的,因为它不知道用户是否输入了某个位置然后清除了输入。
AutocompleteSupportFragment确实具有setText方法来设置要在搜索输入字段中显示的文本。但似乎没有相应的getText方法。
是否有任何方法可以验证AutocompleteSupportFragment是否选择了位置或为空?
.xml
<fragment android:id="@+id/create_event_location_frag"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.libraries.places.widget.AutocompleteSupportFragment" />
Activity.java
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
// Updating my class variables here doesn't help.
// If user first selects a place, then clears it and click "Create",
// I won't know that the location field is empty.
Log.i(TAG, "Place: " + place.getName() + ", " + place.getId());
}
@Override
public void onError(Status status) {
Log.i(TAG, "An error occurred: " + status);
}
});
最佳答案
您的理解是正确的,因为当前没有“ setOnPlaceUnselectedListener”或“ getText”或任何其他通过Places SDK可以帮助您验证输入是否为空的方法。
但是,有一个相关的功能请求,要求在Google的问题跟踪器中公开onClearListener()
,建议您加注星标以增加可见性并订阅通知:
https://issuetracker.google.com/issues/35828573
此外,其中之一中提到了“ hack”或变通办法,以获取清除按钮的View
。请注意,对于AutocompleteSupportFragment
,按钮的ID为places_autocomplete_clear_button
。
因此,例如,您可以创建一个类变量:
private String selectedPlace = null;
并将其用作何时选择或未选择位置的标记。
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
selectedPlace = place.getName();
}
@Override
public void onError(Status status) {
selectedPlace = null;
}
});
View clearButton = autocompleteFragment.getView().findViewById(R.id.places_autocomplete_clear_button);
clearButton.setOnClickListener(view -> {
autocompleteFragment.setText("");
selectedPlace = null;
});
final Button button = findViewById(R.id.button_id);
button.setOnClickListener(v -> {
if (selectedPlace == null) {
Toast.makeText(getApplicationContext(), "Location cannot be empty", Toast.LENGTH_LONG).show();
}
});
我已经对此进行了测试,因此我可以确认它是否有效,希望对您有所帮助!