现在DialogFragment已经完全取代Dialog了,DialogFragment怎么玩呢?有三点需要注意:1、DialogFragment怎么使用;2、DialogFragment怎么与Fragment通信;3、DialogFragment使用过程中遇到的坑及解决办法。
一、DialogFragment如何使用?
跟Fragment使用方法类似,需要实现几个重要的父类方法(onCreate,onCreateView,onViewCreate、onAttach、onKey等)
2、其中onCreate主要用于接收Fragment或Activity传递过来的值
@Override
public void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NO_FRAME, R.style.ThemeHolo);
if (getArguments() != null && getArguments().getString("from") != null) {
type = getArguments().getString("from");
}
}
需要注意的是,
要在onCreate第一句setStyle,否则会显示标题栏等一系列UI问题。
3、onCreateView主要用于加载layout布局
@Nullable
@Override
public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
return inflater.inflate(R.layout.multi_destination_layout, container, false);
}
4、onAttach主要用于获取context。在网上找了各种blog,总结来说,最推荐的方式就是通过onAttach获取context了。
5、onKey主要用于屏蔽back键,这在DialogFragment中使用得非常多。
在onviewCreate中加入
this.getDialog().setOnKeyListener(this);
@Override
public boolean onKey(DialogInterface dialogInterface, int i, KeyEvent keyEvent) {
if (i == KeyEvent.KEYCODE_BACK) {
return true;
} else {
return false;
}
}
二、DialogFragment与Fragment如何通信?
(1)Fragment中启动DialogFragment:
MultiDestinationDialog dialog = new MultiDestinationDialog();
dialog.setTargetFragment(fragment, MultiDestinationUtils.REQUEST_MULTI_DESTINATION);
Bundle bundle = new Bundle();
bundle.putString("from", "click");
dialog.setArguments(bundle);
(2)
DialogFragment向Fragment传值:
private void setResult(City cityInfo) {
if (getTargetFragment() == null) {
return;
} else {
Intent intent = new Intent();
intent.putExtra(MultiDestinationUtils.RESPONSE_CITY_INFO, cityInfo);
getTargetFragment().onActivityResult(MultiDestinationUtils.REQUEST_MULTI_DESTINATION, Activity.RESULT_OK, intent);
}
}
(3)
DialogFragment向Fragment传值:
@Override
public void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
DdtLogUtil.e("LocalHomeFragment执行onActivityResult");
if (MultiDestinationUtils.REQUEST_MULTI_DESTINATION == requestCode) {
// TODO: 2017/8/7 默认CITY_ID应该为多少
City cityInfo = (City) data.getSerializableExtra(MultiDestinationUtils.RESPONSE_CITY_INFO);
DdtLogUtil.e(TAG, "multi_city_id=" + cityInfo.getCityId());
DdtLogUtil.e(TAG, "multi_city_name=" + cityInfo.getCityName());
//多目的地头部设置
setHeader(true, cityInfo.getCityName(), cityInfo.getEnCityName());
getHomeNavigationData(false, true);//获取首页导航数据
getWeatherOfHome(false, true);//获取天气数据
getHomeAlbumData(false, true);//获取营销专辑数据
getHomeShowCoupon();//显示优惠券逻辑
controlWhetherGetRecommendData(false, true);
}
}