DialogFragment实现右侧、中间、底部菜单

本文介绍了一个自定义的Android菜单对话框Fragment组件,可根据不同位置参数调整显示位置,并使用JSONArray传递菜单项数据。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

效果图

  

实现

public class MenuDialogFragment extends DialogFragment {

    private String mPosition;
    private JSONArray mItems;

    @Override
    public Dialog onCreateDialog(Bundle savedInstanceState) {
        LayoutInflater inflater = getActivity().getLayoutInflater();
        View view = inflater.inflate(R.layout.menu_dialog_layout, null);
        ListView listView = (ListView) view.findViewById(R.id.menu_item_lv);

        MenuDialogAdapter adapter = new MenuDialogAdapter(getActivity());
        adapter.buildMenuItems(mPosition, mItems);
        listView.setAdapter(adapter);

        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity(), android.R.style.Theme_DeviceDefault_Dialog);
        builder.setView(view);
        return builder.create();
    }

    @Override
    public void onStart() {
        super.onStart();

        Window window = getDialog().getWindow();
        WindowManager.LayoutParams params = window.getAttributes();
        if ("top".equals(mPosition)) {
            params.x = dip2px(getActivity(), 10);
            params.y = dip2px(getActivity(), 50);
            params.width = window.getWindowManager().getDefaultDisplay().getWidth() / 2;
            params.gravity = Gravity.TOP | Gravity.RIGHT;
        } else if ("center".equals(mPosition)) {
            params.gravity = Gravity.CENTER;
        } else {
            params.width = WindowManager.LayoutParams.MATCH_PARENT;
            params.gravity = Gravity.BOTTOM;
        }
        window.setAttributes(params);
        window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
    }

    @Override
    public void setArguments(Bundle args) {
        try {
            mPosition = args.getString("position");
            mItems = new JSONArray(args.getString("items"));
        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    private int dip2px(Context context, float dpValue) {
        float scale = context.getResources().getDisplayMetrics().density;
        return (int) (dpValue * scale + 0.5f);
    }
}
调用

MenuDialogFragment menuDialog = new MenuDialogFragment();
Bundle bundle = new Bundle();
bundle.putString("position", position);
bundle.putString("items", items.toString());
menuDialog.setArguments(bundle);
menuDialog.show(getActivity().getFragmentManager(), "MenuDialogFragment");

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值