对比Toast使用 1. Toast显示提示框,但这个提示框会在几秒后自动消失。 Eg:Toast.makeText(this, getString(R.string.toastString),//从资源文件string.xml中提取字符串数据 Toast.LENGTH_LONG).show(); 2. AlertDialog弹出框。 public class altertdialogActivity extends Activity implements OnClickListener { //实现OnClickListener接口 //声明变量 private Button toastButton,alertdialogButton,alertdialogButton2; @Override public void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.main); //根据控件ID得到控件的对象 toastButton=(Button)findViewById(R.id.toast); alertdialogButton=(Button)findViewById(R.id.alertdialog); alertdialogButton2=(Button)findViewById(R.id.alertdialog_layout); toastButton.setOnClickListener(this); alertdialogButton.setOnClickListener(this); alertdialogButton2.setOnClickListener(this); } /**复写onClick方法,统一处理按钮事件; * @see android.view.View.OnClickListener#onClick(android.view.View) */ @Override public void onClick(View v) { if(v==this.toastButton){ //点击toastButton按钮时事件响应 Toast.makeText(this, getString(R.string.toastString),//从资源文件string.xml中提取字符串数据 Toast.LENGTH_LONG).show(); } else if (v==this.alertdialogButton) { //点击alertdialogButton按钮时事件响应 showAlertDialog(this); } else if (v==this.alertdialogButton2) { showAlertDialog(this, // LayoutInflater.from(this) //传入一个LayoutInflater对象,这两种方法都可以 (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE) ); } } /**显示基本的AlterDialog * @param context 上下文对象 */ public void showAlertDialog(Context context) { AlertDialog.Builder builder=new AlertDialog.Builder(context); builder.setIcon(R.drawable.icon); //设置图标 builder.setTitle("Android提示框标题"); //设置提示标题 builder.setMessage("这里是提示框里的内容!"); //设置提示内容 //在提示框中添加一个确定的按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.out.println("You Click the PositiveButton"); setTitle("PositiveButton"); } }); //在提示框中添加一个取消的按钮 builder.setNegativeButton("取消", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { System.out.println("You Click NegativeButton"); setTitle("NegativeButton"); } }); builder.show();// 弹出提示框 } /**显示基于Layout的AlertDialog * * @param context 上下文对象 * @param inflater LayoutInflater对象 */ public void showAlertDialog(Context context,LayoutInflater layoutinflater) { View layoutView=layoutinflater.inflate( R.layout.alertdialog_layout, //自定义的xml布局文件,包含一TextView和一EditText。 null); final EditText et=(EditText)layoutView.findViewById(R.id.content);//根据ID得到EditText对象 Builder builder=new Builder(context); builder.setIcon(R.drawable.icon); //设置图标 builder.setTitle("基于Layout的提示框标题"); //设置提示框标题 builder.setView(layoutView); //设置自定义的View作为Dialog的内容 //在提示框中添加一个确定的按钮 builder.setPositiveButton("确定", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { setTitle(et.getText().toString()); //设置Activity的标题 } }); builder.show();//弹出提示框 } } , 点击确定按钮后,更改Activity的标题=》 |