Fragment作为Android 3.0的重要新特性Android123已经使用了三篇文章进行介绍,如果你还不知道Fragment可以先通过Fragment对比Activity – Android碎片介绍一文了解,今天有关Fragment的子类DialogFragment完整的示例工程代码我们一起来看看:
警告窗口 FragmentAlertDialog
public class FragmentAlertDialog extends Activity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_dialog);
View tv = findViewById(R.id.text);
((TextView)tv).setText("Android123-DialogFragment Samples");
Button button = (Button)findViewById(R.id.show);
button.setOnClickListener(new OnClickListener() {
public void onClick(View v) {
showDialog();
}
});
}
void showDialog() {
DialogFragment newFragment = MyAlertDialogFragment.newInstance( "Info");
newFragment.show(getFragmentManager(), "Title");
}
public void doPositiveClick() {
Log.i("FragmentAlertDialog", "左键按下");
}
public void doNegativeClick() {
Log.i("FragmentAlertDialog", "右键按下");
}
public static class MyAlertDialogFragment extends DialogFragment {
public static MyAlertDialogFragment newInstance(int title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putInt("title", title);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
int title = getArguments().getInt("title");
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.icon)
.setTitle(title)
.setPositiveButton("ok",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doPositiveClick();
}
}
)
.setNegativeButton(R.string.alert_dialog_cancel,
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
((FragmentAlertDialog)getActivity()).doNegativeClick();
}
}
)
.create();
}
}
}
上面涉及的fragment_dialog.xml布局文件代码为:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:padding="4dip"
android:gravity="center_horizontal"
android:layout_width="match_parent" android:layout_height="match_parent">
<TextView
android:id="@+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:layout_gravity="center_vertical|center_horizontal"
android:textAppearance="?android:attr/textAppearanceMedium"
android:gravity="top|center_horizontal" />
<Button android:id="@+id/show"
android:layout_width="wrap_content" android:layout_height="wrap_content"
android:layout_weight="0"
android:text="@string/show">
<requestFocus />
</Button>
</LinearLayout>
RSS