最近在学习android,所以就注意到了showDialog这个函数在API 13以上就开始不支持了,所以就想找到新的使用方法,新的使用方法比喜欢使用showDialog复杂
现在就说一下解决方法吧。。。。
显示一个dialog有两种方法(我了解到了,有的可以想我补充):
1.新建一个dialog,如AlertDialog.Builder,接着调用这个新建的dialog的show()方法显示即可,这个很简单
2.上面说到了方法,调用showDialog()方法,接着会调用到onCreateDialog()方法,这种方法是老的,新的方法是
(给出链接:http://developer.android.com/reference/android/app/DialogFragment.html#AlertDialog)
package com.example.first; import android.os.Bundle; import android.annotation.SuppressLint; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.app.DialogFragment; import android.content.DialogInterface; import android.util.Log; import android.view.Menu; import android.view.View; import android.view.View.OnClickListener; import android.widget.Button; import android.widget.Toast; public class Hello extends Activity { private String tag = "lifestyle"; CharSequence[] item = {"Google","Apple","Microsoft"}; boolean[] itemChecked = new boolean[item.length]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_hello); final Button button1 = (Button)findViewById(R.id.button1); button1.setOnClickListener(new OnClickListener(){ public void onClick(View v) { showDialog(); } }); } @SuppressLint("NewApi") public static class MyAlertDialogFragment extends DialogFragment { @SuppressLint("NewApi") public static MyAlertDialogFragment newInstance(int title) { MyAlertDialogFragment frag = new MyAlertDialogFragment(); Bundle args = new Bundle(); args.putInt("title", title); frag.setArguments(args); return frag; } } @SuppressLint("NewApi") void showDialog() { DialogFragment newFragment = MyAlertDialogFragment.newInstance(0); newFragment.show(getFragmentManager(), "dialog"); } public void doPositiveClick() { // Do stuff here. Log.i("FragmentAlertDialog", "Positive click!"); } public void doNegativeClick() { // Do stuff here. Log.i("FragmentAlertDialog", "Negative click!"); } @Override public Dialog onCreateDialog(Bundle savedInstanceState)//这里是按照android开发文档来写的,但是我这里是报错的??? { int title = getArguments().getInt("title"); //switch(id){ //case 0: return new AlertDialog.Builder(this) .setIcon(R.drawable.ic_launcher) .setTitle("Hello World") .setPositiveButton("OK", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface arg0, int arg1) { Toast.makeText(getBaseContext(), "OK clicked", Toast.LENGTH_SHORT).show(); } }) .setNegativeButton("Cancel", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { Toast.makeText(getBaseContext(), "Cancel clicked", Toast.LENGTH_SHORT).show(); } }) .setMultiChoiceItems(item, itemChecked, new DialogInterface.OnMultiChoiceClickListener() { @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { Toast.makeText(getBaseContext(), item[which]+(isChecked?"checked":"unchecked"), Toast.LENGTH_SHORT).show(); } }).create(); //} //return null; } }