这是个展示dialog窗口的fragment。这个fragment包含了一个Dialog对象,它的展示是基于fragment的状态。控制dialog(决定要show,hide,dismiss等)应该通过dialogfragment的api而不是dialog的
实现这个类需要通过override方法onCreateView(LayoutInflater, ViewGroup, Bundle)来填充dialog的内容。另外,可以override方法onCreateDialog(Bundle)来创建一个完全自定义的dialog。
生命周期:
DialogFragment做了很多事情来控制fragment的生命周期,而不是dialog的。注意dialog是完全自主的,它有自己的window,接收自己的输入事件,经常自己决定什么时候消失(通过back键或者用户点击dialog上的button)。
DialogFragment需要保证Fragment和Dialog的状态保持一致。它监听dialog的dissmiss event,并且去处理自己的状态。这意味着应该调用 show(FragmentManager, String)或者show(FragmentTransaction, String)来添加一个DialogFragment的实例给UI层,并且它自主将remove当dialog消失的时候。
DialogFragment说到底还是个fragment,它爹能干的事情它也都能做,所以也可以是 通过ft.addToBackStack(null)压倒栈中,通过back键逐个resume,也可以被嵌套到更大层的UI中。
下面是个简单的dialog fragment:
- public static class MyDialogFragment extends DialogFragment {
- static MyDialogFragment newInstance() {
- return new MyDialogFragment();
- }
- @Override
- public View onCreateView(LayoutInflater inflater, ViewGroup container,
- Bundle savedInstanceState) {
- View v = inflater.inflate(R.layout.hello_world, container, false);
- View tv = v.findViewById(R.id.text);
- ((TextView)tv).setText("This is an instance of MyDialogFragment");
- return v;
- }
- }
public static class MyDialogFragment extends DialogFragment {
static MyDialogFragment newInstance() {
return new MyDialogFragment();
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.hello_world, container, false);
View tv = v.findViewById(R.id.text);
((TextView)tv).setText("This is an instance of MyDialogFragment");
return v;
}
}
下面是按照dialog形式来显示:
- void showDialog() {
- // Create the fragment and show it as a dialog.
- DialogFragment newFragment = MyDialogFragment.newInstance();
- newFragment.show(getFragmentManager(), "dialog");
- }
void showDialog() {
// Create the fragment and show it as a dialog.
DialogFragment newFragment = MyDialogFragment.newInstance();
newFragment.show(getFragmentManager(), "dialog");
}
下面是添加到另一个view布局中
- FragmentTransaction ft = getFragmentManager().beginTransaction();
- DialogFragment newFragment = MyDialogFragment.newInstance();
- ft.add(R.id.embedded, newFragment);
- ft.commit();
FragmentTransaction ft = getFragmentManager().beginTransaction();
DialogFragment newFragment = MyDialogFragment.newInstance();
ft.add(R.id.embedded, newFragment);
ft.commit();
看了百度新闻的dialog和自身UI框架是挺一致的。下面是根据它的样式的模拟的代码。
先看看style
- <style name="DialogStyle" parent="@android:style/Theme.Dialog">
- <item name="android:windowBackground">@drawable/settings_window</item>
- <item