PlaceAutocompleteFragment:自动打开SearchView

时间:2017-04-19 16:46:40

标签: android android-layout android-fragments android-view google-places

我想在活动完成加载后立即自动点击片段。

片段定义是:

 <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"
    />

我试过这样做

fragment = findViewById(R.id.place_autocomplete_fragment);

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            fragment.performClick();
        }
    }, 1000);

但它没有用。

有没有办法自动点击片段?

编辑: 就我而言,片段被

夸大了
//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);
        }
    });

2 个答案:

答案 0 :(得分:5)

您无法点击<fragment>

点击事件只有View可以拥有的内容。片段 a View

您可以点击片段膨胀的View

@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());
}

更新

因为您使用的是来自Play服务的PlaceAutocompleteFragment(因此您没有来源),所以您可以在活动中执行以下操作:

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.place_autocomplete_search_input)
                .performClick();
    }
});

答案 1 :(得分:1)

科特琳: 适用于最新的Places api 2.4.0(com.google.android.libraries.places:places:2.4.0) 您可以通过以下代码获取视图,然后在searchview上单击:

val root: View = autocompleteSupportFragment?.view!!
root.findViewById<View>(R.id.places_autocomplete_search_input).performClick()