简体   繁体   中英

How to start activity from bottom sheet fragment

I just started working with bottomSheetDialog for android. I have been able to show the bottomSheet correctly but I need to start an activity from clicking on any of the items. How do I go about this?

MainFragment.java

public class MainFragment extends Fragment {
private BottomSheetDialog bottomSheetDialog;
    public SearchFragment() {
        // Required empty public constructor
    }


    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        // Inflate the layout for this fragment
        View view =  inflater.inflate(R.layout.fragment_search, container, false);
        all.setOnClickListener(v -> {
//open bottom sheet from fragment
          BottomSheetDialog bottomSheetDialog = new BottomSheetDialog();
          bottomSheetDialog.show(Objects.requireNonNull(getActivity()).getSupportFragmentManager(), "bottomSheet");
        });
        return view;
    }

BottomSheetDialogFrament.java

public class BottomSheetDialog extends BottomSheetDialogFragment {
        private BottomSheetListener bottomSheetListener;
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View  v = inflater.inflate(R.layout.bottom_sheet_layout, container, false);
            LinearLayout mRestaurants = v.findViewById(R.id.restaurants);
            mRestaurants.setOnClickListener(v1 -> {
//need to start activity from here
                Intent intent = new Intent(getActivity(), MapActivity.class);
                intent.putExtra("mapData", "Restaurants");
                startActivity(intent);
            });
            return v;
        }

        }
    }

did you try getting context from your view?

public class BottomSheetDialog extends BottomSheetDialogFragment {
        private BottomSheetListener bottomSheetListener;
        @Nullable
        @Override
        public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
            View  v = inflater.inflate(R.layout.bottom_sheet_layout, container, false);
            LinearLayout mRestaurants = v.findViewById(R.id.restaurants);
            mRestaurants.setOnClickListener(v1 -> {
//need to start activity from here
                Intent intent = new Intent(getActivity(), MapActivity.class);
                intent.putExtra("mapData", "Restaurants");
                v1.getContext().startActivity(intent);
            });
            return v;
        }

        }
    }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM