学习Android过程中发现showDialog()、onCreateDialog()这些方法从Android4.0开始都过时了。
官方推荐使用DialogFragment类来创建对话框。
1)布局文件dialog_activity.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" > <Button
android:id="@+id/btn_dialog"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="@string/btn_dialog_text"
android:layout_gravity="center_horizontal"/>
</LinearLayout>
2)Activity代码
package cn.luxh.dialognew; import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.app.DialogFragment;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.Button;
import android.widget.Toast; public class DialogActivity extends Activity{ private static final String TAG = "DialogActivity"; private Button btn_Dialog; @Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_activity);
handleButtonClick();
} /**
* 处理按钮事件
*/
private void handleButtonClick() {
btn_Dialog = (Button) findViewById(R.id.btn_dialog);
btn_Dialog.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
AlertDialogFragment alertDialogFragment = AlertDialogFragment.newInstance();
//显示对话框
alertDialogFragment.show(getFragmentManager(), "MyDialog");
}
});
} /**
* 确定按钮事件处理
*/
private void doPositiveClick() {
Log.d(TAG, "确定按钮事件处理");
Toast.makeText(this, "确定按钮被点击!", Toast.LENGTH_SHORT).show();
} /**
* 取消按钮事件处理
*/
private void doNegativeClick(){
Log.d(TAG, "取消按钮事件处理");
Toast.makeText(this, "取消按钮被点击!", Toast.LENGTH_SHORT).show();
} /**
* 生成对话框
*/
public static class AlertDialogFragment extends DialogFragment{ private static AlertDialogFragment alertDialogFragment = new AlertDialogFragment(); public static AlertDialogFragment newInstance() {
return alertDialogFragment;
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
return new AlertDialog.Builder(getActivity())
.setIcon(R.drawable.ic_launcher)
.setTitle("我的对话窗口")
.setPositiveButton("确定", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((DialogActivity)getActivity()).doPositiveClick();
}
})
.setNegativeButton("取消", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
((DialogActivity)getActivity()).doNegativeClick();
}
}).create();
}
}
}
3)运行效果