片段中需要java方法调用

ghhkc1vu  于 2021-07-09  发布在  Java
关注(0)|答案(1)|浏览(341)

我是android新手,所以请帮帮我。我想打开另一个片段中带有map的片段,所以我在第一个片段中做了一个事务:

View rootView = inflater.inflate(R.layout.fragment_location, container, false);

    btn = rootView.findViewById(R.id.btn);
    btn.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            MapsFragment gMaps = new MapsFragment();
            assert getFragmentManager() != null;
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.mainlayout, gMaps()); //HERE IS A PROBLEM
            transaction.commit();
        }
    });
    return rootView;

当gmaps()被调用时,它会显示一个错误的方法调用屏幕截图
下面是mapsfragment.java代码

public class MapsFragment extends FragmentActivity implements OnMapReadyCallback, APIService.fetchResults {
private GoogleMap mMap;
private APIService apiService;
private IntentFilter connectivityIntentFilter;
private BottomSheetDialog bottomSheetDialog;
private View dialogView;
private Boolean isOpenOnly;
private Integer maxPrice;
private Integer radius;
private Place previousPlace;
private BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
    @Override
    public void onReceive(Context context, Intent intent) {
        if (!NetworkChecker.getInstance().isNetworkAvailable(context)) {
            Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_active_connection), Snackbar.LENGTH_SHORT).show();
        }
    }
};

@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.fragment_maps);
    apiService = new APIService(this);
    connectivityIntentFilter = new IntentFilter(CONNECTIVITY_ACTION);
    GooglePlayServiceChecker googlePlayServiceChecker = new GooglePlayServiceChecker();

    if (!googlePlayServiceChecker.checkGooglePlayServices(this)) {
        Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_google_play_services), Snackbar.LENGTH_SHORT).show();
        finish();
}
    final SupportMapFragment mapFragment = (SupportMapFragment) getSupportFragmentManager()
            .findFragmentById(R.id.map);
    assert mapFragment != null;
    mapFragment.getMapAsync(this);

    PlaceAutocompleteFragment autocompleteFragment = (PlaceAutocompleteFragment) getFragmentManager().findFragmentById(R.id.place_autocomplete);

    AutocompleteFilter typeFilter = new AutocompleteFilter.Builder()
            .setTypeFilter(AutocompleteFilter.TYPE_FILTER_REGIONS)
            .build();
    autocompleteFragment.setFilter(typeFilter);
    autocompleteFragment.setHint(getString(R.string.default_city));
    autocompleteFragment.setOnPlaceSelectedListener(new PlaceSelectionListener() {

        @Override
        public void onPlaceSelected(Place place) {
            String s = (String) place.getName();

            //Update place data.
            previousPlace = place;

            apiService.getPlaceSearch(s, getString(R.string.place_type), radius, maxPrice, isOpenOnly);
        }

        @Override
        public void onError(Status status) {

        }
    });

    bottomSheetDialog = new BottomSheetDialog(MapsFragment.this);
    dialogView = getLayoutInflater().inflate(R.layout.bottom_sheet, null);
    bottomSheetDialog.setContentView(dialogView);

    FloatingActionButton floatingActionButton = findViewById(R.id.fab_filter);
    floatingActionButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            dialogView.setVisibility(View.VISIBLE);
            bottomSheetDialog.show();
        }
    });

    final Switch swOpenOnly = dialogView.findViewById(R.id.openCloseSwitch);
    final SeekBar skRadius = dialogView.findViewById(R.id.seekbar_radius);
    final SeekBar skPrice = dialogView.findViewById(R.id.seekbar_price);

    dialogView.findViewById(R.id.bt_submit_filter).setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {

            radius = skRadius.getProgress();
            maxPrice = skPrice.getProgress();
            isOpenOnly = swOpenOnly.isChecked();

            bottomSheetDialog.dismiss();

            //Get places using filter.
            if (previousPlace == null) {
                apiService.getPlaceSearch(getString(R.string.default_city), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
            } else {
                apiService.getPlaceSearch(previousPlace.getName().toString(), getString(R.string.place_type), radius, maxPrice, isOpenOnly);
            }
        }
    });
}
@Override
public void onPointerCaptureChanged(boolean hasCapture) {

}
@Override
public void parseResults(Result result) {
    mMap.clear();
    if (result != null && result.getStatus() != null && result.getStatus().equals("OK")) {

        LatLngBounds.Builder builder = new LatLngBounds.Builder();

        for (Restaurant restaurant : result.getRestaurants()) {
            Location pastLocation = restaurant.getGeometry().getLocation();

            LatLng latLng = new LatLng(pastLocation.getLatitude(), pastLocation.getLongitude());
            MarkerOptions markerOptions = new MarkerOptions()
                    .position(latLng)
                    .title(restaurant.getName())
                    .snippet(restaurant.getFormattedAddress());

            Marker m = mMap.addMarker(markerOptions);
            m.setTag(restaurant.getResID());
            mMap.moveCamera(CameraUpdateFactory.newLatLng(latLng));
            builder.include(m.getPosition());
        }

        try {
            LatLngBounds latLngBounds = builder.build();
            int padding = 10;
            CameraUpdate cu = CameraUpdateFactory.newLatLngBounds(latLngBounds, padding);
            mMap.animateCamera(cu);
        } catch (IllegalStateException | ParseException | NullPointerException e) {
            //Don't move
        }
    } else {
        Snackbar.make(findViewById(R.id.main_map), getString(R.string.error_message), Snackbar.LENGTH_SHORT).show();
    }
}
@Override
public void onMapReady(GoogleMap googleMap) {
    mMap = googleMap;

    if (!NetworkChecker.getInstance().isNetworkAvailable(this))
        Snackbar.make(findViewById(R.id.main_map), getString(R.string.no_active_connection), Snackbar.LENGTH_SHORT).show();
    else
        apiService.getPlaceSearch(getString(R.string.default_city), getString(R.string.place_type), radius, maxPrice, isOpenOnly);

    mMap.setOnInfoWindowClickListener(marker -> {
        Intent i = new Intent(MapsFragment.this, DetailActivity.class);
        i.putExtra(getString(R.string.intent_key_id_tag), marker.getTag().toString());

        if (NetworkChecker.getInstance().isNetworkAvailable(MapsFragment.this))
            startActivity(i);
    });
}
@Override
protected void onResume() {
    super.onResume();
    registerReceiver(broadcastReceiver, connectivityIntentFilter);
}

@Override
protected void onPause() {
    super.onPause();
    unregisterReceiver(broadcastReceiver);
}

}
我不知道这是否有意义,但还好。如何解决这个问题?
截图2

jqjz2hbq

jqjz2hbq1#

你可能在用 android.app.FragmentTransaction . 尝试使用 androidx.fragment.app.FragmentTransaction 以及 getSupportFragmentManager().beginTransaction() .
比如:

androidx.fragment.app.FragmentTransaction transaction = getSupportFragmentManager().beginTransaction();
    MapsFragment gMaps = new MapsFragment();
    assert getFragmentManager() != null;
    transaction.replace(R.id.mainlayout, gMaps).commit();

相关问题