底部弹出DialogFragment+与Activity数据交互

先贴上效果图:


底部弹出DialogFragment+与Activity数据交互_第1张图片
效果图.jpg

实现步骤特别简单:
1.新建DialogFragment类,在OnCreateView中返回你自定义的view.

public class ADDialogFragment extends DialogFragment{
  @Override
  public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
      //加这句话去掉自带的标题栏
      getDialog().requestWindowFeature(Window.FEATURE_NO_TITLE);
      View view = inflater.inflate(R.layout.dialogfragment_person, null);
      //init(view);
      return view;
  }
}

自定义dialogfragment_person的布局文件如下:



    
    
    
    
    

在MainActivity的Button(或ImageView或其他)的点击事件中作如下处理即可弹出dialogfragment:

ADDialogFragment dialogFragment = new ADDialogFragment();
dialogFragment.show(getFragmentManager(),"android");

ok了,这时你会发现它显示在页面中央,但是我们想让dialogfragment显示到页面底部,那么只需在DialogFragment中添加如下代码即可:

@Override
public void onStart() {
    super.onStart();
    Window window = getDialog().getWindow();
    WindowManager.LayoutParams params = window.getAttributes();
    params.gravity = Gravity.BOTTOM;
    params.width = WindowManager.LayoutParams.MATCH_PARENT;
    window.setAttributes(params);
    //设置背景透明
    window.setBackgroundDrawable(new ColorDrawable(Color.TRANSPARENT));
}

最后一步:传递数据到MainActivity中:
在dialogfragment中:

public interface OnDialogListener {
    void onDialogClick(String person);
}
public void setOnDialogListener(OnDialogListener dialogListener){
    this.mlistener = dialogListener;
}

在Textview的点击事件中:

public OnDialogListener mlistener;
@Override
public void onClick(View view) {
    switch (view.getId()) {
        case R.id.tv1:
            mlistener.onDialogClick("1");
            dismiss();
            break; 
       case R.id.tv2:
            mlistener.onDialogClick("2");
            dismiss();
            break;
        case R.id.tv3:
            mlistener.onDialogClick("3");
            dismiss();
            break;
        case R.id.tv4:
            mlistener.onDialogClick("4");
            dismiss();
            break;
    }
}

在MainActivity中实现此接口即可:

dialogFragment.setOnDialogListener(new PersonDialogFragment.OnDialogListener() {
    @Override
    public void onDialogClick(String person) {
        ToastUtil.showToast(person);
    }
});

你可能感兴趣的:(底部弹出DialogFragment+与Activity数据交互)