I want to automatically click on a fragment as soon as the activity is done loading.
The fragment definition is:
<fragment
android:id="@+id/place_autocomplete_fragment"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:name="com.google.android.gms.location.places.ui.PlaceAutocompleteFragment"
/>
I have tried doing this
fragment = findViewById(R.id.place_autocomplete_fragment);
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
fragment.performClick();
}
}, 1000);
but it didnt work.
Is there any way to click automatically on a fragment?
EDIT: In my case, the fragment is inflated by
//PlaceAutoComplete Search Implementation
PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment)
getFragmentManager().findFragmentById(R.id.place_autocomplete_fragment);
autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {
@Override
public void onPlaceSelected(Place place) {
Log.i(String.valueOf(this), "Place: " + place.getName() + "\nID: " + place.getId());
String placeId = place.getId();
try {
Intent intent = new Intent(PlaceSearch.this, PlaceDetailsFromSearch.class);
Bundle extras = new Bundle();
extras.putString("placeID", placeId);
intent.putExtras(extras);
startActivity(intent);
} catch (Exception e) {
e.printStackTrace();
}
}
@Override
public void onError(Status status) {
Log.i(String.valueOf(this), "An error occurred: " + status);
}
});
You cannot click on a <fragment>
.
Click event is something that only View
can have. Fragment is not a View
.
You can click on a View
that your fragment inflates.
@Override
public void onViewCreated(View view, @Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
// some `View` from your fragment
View searchView = view.findViewById(R.id.searchView);
// Dispatch a click event to `searchView` as soon as that view is laid out
searchView.post(() -> searchView.performClick());
}
Because you are using PlaceAutocompleteFragment
which is from Play Services (thus you do not have sources), you can do something like this in your activity:
final PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager()
.findFragmentById(R.id.place_autocomplete_fragment);
final View root = autocompleteFragment.getView();
root.post(new Runnable() {
@Override
public void run() {
root.findViewById(R.id.places_autocomplete_search_input)
.performClick();
}
});