在design包裡面 有一個 BottomSheetDialogFragment 這個Fragment,他已經幫我們處理好了手勢,所以實現起來很簡單。下麵是代碼: ...
在design包裡面 有一個 BottomSheetDialogFragment 這個Fragment,他已經幫我們處理好了手勢,所以實現起來很簡單。下麵是代碼:
public class ItemListDialogFragment extends BottomSheetDialogFragment { // TODO: Customize parameter argument names private static final String ARG_ITEM_COUNT = "item_count"; private Listener mListener; // TODO: Customize parameters public static ItemListDialogFragment newInstance(int itemCount) { final ItemListDialogFragment fragment = new ItemListDialogFragment(); final Bundle args = new Bundle(); args.putInt(ARG_ITEM_COUNT, itemCount); fragment.setArguments(args); return fragment; } @Nullable @Override public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) { // 在這裡將view的高度設置為精確高度,即可屏蔽向上滑動不占全屏的手勢。 View view = inflater.inflate(R.layout.fragment_item_list_dialog, container, false); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ScreenUtils.getScreenHeight(getActivity()) / 3 * 2)); return view; } @Override public void onViewCreated(View view, @Nullable Bundle savedInstanceState) { final RecyclerView recyclerView = (RecyclerView) view; recyclerView.setLayoutManager(new LinearLayoutManager(getContext())); recyclerView.setAdapter(new ItemAdapter(getArguments().getInt(ARG_ITEM_COUNT))); } @Override public void onAttach(Context context) { super.onAttach(context); final Fragment parent = getParentFragment(); if (parent != null) { mListener = (Listener) parent; } else { mListener = (Listener) context; } } @Override public void onDetach() { mListener = null; super.onDetach(); } public interface Listener { void onItemClicked(int position); } private class ViewHolder extends RecyclerView.ViewHolder { final TextView text; ViewHolder(LayoutInflater inflater, ViewGroup parent) { // TODO: Customize the item layout super(inflater.inflate(R.layout.fragment_item_list_dialog_item, parent, false)); text = (TextView) itemView.findViewById(R.id.text); text.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { if (mListener != null) { mListener.onItemClicked(getAdapterPosition()); dismiss(); } } }); } } private class ItemAdapter extends RecyclerView.Adapter<ViewHolder> { private final int mItemCount; ItemAdapter(int itemCount) { mItemCount = itemCount; } @Override public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) { return new ViewHolder(LayoutInflater.from(parent.getContext()), parent); } @Override public void onBindViewHolder(ViewHolder holder, int position) { holder.text.setText(String.valueOf(position)); } @Override public int getItemCount() { return mItemCount; } } }