Android学习笔记(七)——显示对话框窗体
显示对话框窗体
1、创建Dialog1项目,在activity_main.xml文件里加入一个Button:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:tools="http://schemas.android.com/tools" android:layout_width="match_parent" android:layout_height="match_parent" android:paddingBottom="@dimen/activity_vertical_margin" android:paddingLeft="@dimen/activity_horizontal_margin" android:paddingRight="@dimen/activity_horizontal_margin" android:paddingTop="@dimen/activity_vertical_margin" tools:context=".MainActivity" > <Button android:id="@+id/btn_dialog" android:layout_width="fill_parent" android:layout_height="wrap_content" android:onClick="onClick" android:text="Click to display a dialog" /> </RelativeLayout>
2、在MainActivity.java文件里实现创建对话框。加入代码例如以下:
package com.example.dialog; import android.os.Bundle; import android.app.Activity; import android.app.AlertDialog; import android.app.Dialog; import android.content.DialogInterface; import android.view.Menu; import android.view.View; import android.widget.Toast; public class MainActivity extends Activity { CharSequence[] items = { "Google", "Apple", "Microsoft" }; boolean[] itemsChecked = new boolean[items.length]; @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.activity_main); } @SuppressWarnings("deprecation") public void onClick(View v) { showDialog(0);//点击button时,显示对话框,此方法接受一个整型參数,用来标识要显示的特定对话框(这里仅仅创建了标识为0的对话框)。 } @Override @Deprecated //onCreateDialog()方法是一个用于创建由活动管理的对话框的回调方法。当调用showDialog()时,将调用此回调方法。 protected Dialog onCreateDialog(int id) { // TODO Auto-generated method stub switch (id) { case 0://要创建一个对话框。须要使用AlertDialog类的Builder构造函数来设置不同的属性,如图标、标题、button及复选框等。 return new AlertDialog.Builder(this)//调用AlertDialog对象的Builder构造函数。 .setIcon(R.drawable.ic_launcher) .setTitle("This is a dialog with some simple text...") .setPositiveButton("OK",//设置OKbutton new DialogInterface.OnClickListener() {//设置点击事件 @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Toast.makeText(getBaseContext(), "OK clicked!", Toast.LENGTH_SHORT) .show(); } }) .setNegativeButton("Cancel",//设置Cancelbutton new DialogInterface.OnClickListener() {//设置点击事件 @Override public void onClick(DialogInterface dialog, int which) { // TODO Auto-generated method stub Toast.makeText(getBaseContext(), "Cancel clicked!", Toast.LENGTH_SHORT).show(); } }) .setMultiChoiceItems(items, itemsChecked,//设置复选框 new DialogInterface.OnMultiChoiceClickListener() {//设置点击事件 @Override public void onClick(DialogInterface dialog, int which, boolean isChecked) { // TODO Auto-generated method stub Toast.makeText( getBaseContext(), items[which]//通过传入检验是否点击的參数isChecked来选择返回的消息。+ (isChecked ? " checked!" : " unchecked!"), Toast.LENGTH_SHORT).show(); } }).create(); } return null; } @Override public boolean onCreateOptionsMenu(Menu menu) { // Inflate the menu; this adds items to the action bar if it is present. getMenuInflater().infla