]
///
package com.example.fragmentalertdialogtest;
/**
* 从Android3.0之后,增加Fragment类,该类有一个子类叫DialogFragment类,
* 可以用于显示对话框,本示例就是演示该技术的。
* */
import android.os.Bundle;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.view.View;
import android.widget.Button;
import android.widget.Toast;
public class MainActivity extends Activity {
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Button show = new Button(this);
show.setText("确定");
show.setOnClickListener(new android.view.View.OnClickListener() {
@Override
public void onClick(View v) {
DialogFragment newFragment = MyAlertDialogFragment
.newInstance("天气");
// 把newFragment交给FragmentManager对象,与Activity绑定
// 当对话框dimss后,会自动解除绑定
// 触发MyAlertDialogFragment中的函数onCreateDialog被回调用
newFragment.show(MainActivity.this.getFragmentManager(),
"sdfsdf");
}
});
this.setContentView(show);
}
public static class MyAlertDialogFragment extends DialogFragment {
public static MyAlertDialogFragment newInstance(String title) {
MyAlertDialogFragment frag = new MyAlertDialogFragment();
Bundle args = new Bundle();
args.putString("title", title);
frag.setArguments(args);
return frag;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
String title = this.getArguments().getString("title");
// 取出与this表示的DialogFragment绑定的Activity对象
AlertDialog.Builder builder = new AlertDialog.Builder(
this.getActivity());
builder.setIcon(R.drawable.ic_launcher);
builder.setTitle(title);
// 既定出对话框
builder.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog,
int whichButton) {
}
});
builder.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
// 显示Toast.并退出对话框
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(getActivity(), "睛转多云",
Toast.LENGTH_LONG).show();
}
});
AlertDialog dialog = builder.create();
Button button = new Button(getActivity());
button.setText("显示");
button.setOnClickListener(new View.OnClickListener() {
// 显示Toast,但是对话框不退出
@Override
public void onClick(View v) {
Toast.makeText(v.getContext(), "我是对话框", 1).show();
}
});
dialog.setView(button);
dialog.show();
return dialog;
}
}
}