Android 程式开发:(十三)特殊碎片 —— 13.2 DialogFragment
我们也可以创建另外一种碎片——DialogFragment。顾名思义,DialogFragment就是一个浮动在Activity上面的Fragment。当需要用户的反馈时,DialogFragment就会派上用场。与使用ListFragment类似,需要继承DialogFragment基类。
下面将会展示如何使用DialogFragment。
1. 创建一个工程:DialogFragmentExample。
2. 在包路径下面新建一个类,Fragment1。
[java]
public class Fragment1 extends DialogFragment {
static Fragment1 newInstance(String title) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton("OK",
new DialogInte易做图ce.OnClickListener() {
public void onClick(DialogInte易做图ce dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doPositiveClick();
}
})
.setNegativeButton("Cancel",
new DialogInte易做图ce.OnClickListener() {
public void onClick(DialogInte易做图ce dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doNegativeClick();
}
}).create();
}
}
3. DialogFragmentExampleActivity.java中的代码。
[java]
public class DialogFragmentExampleActivity extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Fragment1 dialogFragment = Fragment1.newInstance(
"Are you sure you want to do this?");
dialogFragment.show(getFragmentManager(), "dialog");
}
public void doPositiveClick() {
//---perform steps when user clicks on OK---
Log.d("DialogFragmentExample", "User clicks on OK");
}
public void doNegativeClick() {
//---perform steps when user clicks on Cancel---
Log.d("DialogFragmentExample", "User clicks on Cancel");
}
}
4. 按F11在模拟器上调试。会看到一个对话框,点击OK或Cancel按钮会弹出消息。
要创建一个DialogFragment,首先要继承DialogFragment基类:
[java]
public class Fragment1 extends DialogFragment{
}
在这个例子中,我没创建一个警告对话框,它包含一条警告消息和两个可供点击的按钮。在Fragment1类中,我们定义了一个newInstance()方法:
[java]
static Fragment1 newInstance(String title) {
Fragment1 fragment = new Fragment1();
Bundle args = new Bundle();
args.putString("title", title);
fragment.setArguments(args);
return fragment;
}
这个newInstance()方法允许创建一个碎片的实例对象,同时,它也可以接受一个指定的字符串参数,这个参数就是对话框中的消息。title对象被存储在一个Bundle对象中,之后会用到它。
接下来,我们定义了onCreateDialog()方法,这个方法在onCreate()之后,onCreateView()之前被调用:
[java]
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = getArguments().getString("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle(title)
.setPositiveButton("OK",
new DialogInte易做图ce.OnClickListener() {
public void onClick(DialogInte易做图ce dialog,
int whichButton) {
((DialogFragmentExampleActivity)
getActivity()).doPositiveClick();
}
})
.setNegativeButton("Cancel",
new DialogInte易做图ce.OnClickListener() {
&nb
补充:移动开发 , Android ,