底部弹出DialogFragment+与Activity数据交互
字数153阅读312评论0喜欢2
先贴上效果图:
效果图.jpg
实现步骤特别简单:
1.新建DialogFragment类,在OnCreateView中返回你自定义的view.
publicclassADDialogFragmentextendsDialogFragment{@OverridepublicViewonCreateView(LayoutInflaterinflater,ViewGroupcontainer,BundlesavedInstanceState) {//加这句话去掉自带的标题栏getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);Viewview = inflater.inflate(R.layout.dialogfragment_person,null);//init(view);returnview; }}
自定义dialogfragment_person的布局文件如下:
在MainActivity的Button(或ImageView或其他)的点击事件中作如下处理即可弹出dialogfragment:
ADDialogFragmentdialogFragment =newADDialogFragment();dialogFragment.show(getFragmentManager(),"android");
ok了,这时你会发现它显示在页面中央,但是我们想让dialogfragment显示到页面底部,那么只需在DialogFragment中添加如下代码即可:
@OverridepublicvoidonStart(){ super.onStart(); Window window = getDialog().getWindow(); WindowManager.LayoutParamsparams= window.getAttributes();params.gravity = Gravity.BOTTOM;params.width = WindowManager.LayoutParams.MATCH_PARENT; window.setAttributes(params);//设置背景透明window.setBackgroundDrawable(newColorDrawable(Color.TRANSPARENT));}
最后一步:传递数据到MainActivity中:
在dialogfragment中:
publicinterfaceOnDialogListener{voidonDialogClick(String person);}publicvoidsetOnDialogListener(OnDialogListener dialogListener){this.mlistener = dialogListener;}
在Textview的点击事件中:
publicOnDialogListener mlistener;@OverridepublicvoidonClick(View view){switch(view.getId()) {caseR.id.tv1: mlistener.onDialogClick("1"); dismiss();break;caseR.id.tv2: mlistener.onDialogClick("2"); dismiss();break;caseR.id.tv3: mlistener.onDialogClick("3"); dismiss();break;caseR.id.tv4: mlistener.onDialogClick("4"); dismiss();break; }}
在MainActivity中实现此接口即可:
dialogFragment.setOnDialogListener(newPersonDialogFragment.OnDialogListener() {@OverridepublicvoidonDialogClick(String person){ ToastUtil.showToast(person); }});