如何从底页片段开始活动

时间:2019-11-26 08:30:00

标签: java android

我刚刚开始使用bottomSheetDialog for android。我已经能够正确显示bottomSheet,但是我需要通过单击任何项​​目来开始一项活动。我该怎么办?

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;
        }

        }
    }

1 个答案:

答案 0 :(得分:0)

您尝试从视图中获取上下文吗?

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;
        }

        }
    }