我刚刚拿起了 android SDK 和 eclipse 并决定编写一个简单的对话框,当你单击一个按钮时会弹出一个对话框,但是我发现 showDialog() 方法已被弃用,而 DialogFragment 是最好的制作方法一,所以这里是:
package net.learn2develop.dialog;
import android.app.Activity;
import android.app.AlertDialog;
import android.app.Dialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.support.v4.app.DialogFragment;
import android.support.v4.app.FragmentManager;
import android.view.View;
import android.widget.Button;
public class DialogWindow extends Activity{
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog_window);
Button btn = (Button) findViewById(R.id.btn_dialog);
btn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
class MyDialog extends DialogFragment {
FragmentManager fm = getFragmentManager();
public MyDialog() {
}
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
//using the builder class
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
builder.setMessage("Simple Dialog")
.setPositiveButton("nothing", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "ok then", Toast.LENGTH_SHORT).show();
}
})
.setNegativeButton("cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
//Toast.makeText(getBaseContext(), "cancel", Toast.LENGTH_SHORT).show();
}
});
return builder.create();
}
}
MyDialog md = new MyDialog();
md.show(md.fm, "dialog");
}
});
}
}
调试器在以下位置显示错误:
md.show(md.fm, "dialog");
进一步检查,根据调试器中的变量选项卡,fm 变量为空,为什么会这样,是否有更有效的解决方案?我对android很陌生,如果这是一个简单的问题,我很抱歉。