Android提供了丰富的对话框支持,它提供如下4种常用对话框:
AlertDialog
|
实际应用最广泛的对话框
|
ProgressDialog
|
进度对话框,只是对简单进度条的封装
|
DatePickerDialog
|
日期选择对话框
|
TimePickerDialog
|
时间选择对话框
|
2.9.1 AlertDialog
AlertDialog功能很强大,可以生成各种内容的对话框,但实际上,AlertDialog生成的对话框总有一个大致结构,可以分为4个区域:图标区、标题区、内容区、按钮区
从上面的对话框的结构来看,创建对话框需要进过如下几步:
- 使用创建AlertDialog.Builder对象
- 调用AlertDialog.Builder的setTitle()或setCustomTitle()方法设置标题
- 调用AlertDialog.Builder的setIcon()方法设置标题
- 调用AlertDialog.Builder的相关设置方法设置对话框内容
- 调用AlertDialog.Builder的setPositiveButton()、setNegativeButton()或NeutralButton()方法添加多个按钮
- 调用AlertDialog.Builder的create()创建AlertDialog对象,再调用AlertDialog对象的show()将该对话框显示出来
可以看出,第4个步骤是最灵活的,AlertDialog允许创建各种内容的对话框,AlertDialog提供了以下6种方法来制定对话框内容
setMessage()
|
设置为简单文本内容
|
setItems()
|
设置为简单列表项
|
setSingleChoiceItems()
|
设置对话框内容为单选列表项
|
setMultiChoiceItems()
|
设置对话框内容为多选列表项
|
setAdapter() |
设置为自定义列表项
|
setView()
|
自定义View
|
示例代码:
public
class
MainActivity
extends
Activity {
TextView show ;
String[] items = new String[] {
"疯狂Java讲义" , "疯狂Ajax讲义" ,
"轻量级Java EE企业应用实战" ,
"疯狂Android讲义" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu. main , menu);
return true ;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id. action_settings ) {
return true ;
}
return super .onOptionsItemSelected(item);
}
public void simple(View source) {
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "simple alert dialog" )
.setIcon(R.drawable. ic_launcher )
.setMessage( "test content\n secon row content" );
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder)
{
return builder.setPositiveButton( "Sure" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "clicked 'sure' button" );
}
});
}
private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder)
{
return builder.setNegativeButton( "Cancel" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "clicked 'cancel' button" );
}
});
}
public void simpleList(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "simple list dialog" )
.setIcon(R.drawable. ic_launcher )
.setItems( items , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "you pick <" + items [which] + ">" );
}
});
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void singleChoice(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "single choice dialog" )
.setIcon(R.drawable. ic_launcher )
.setSingleChoiceItems( items , 1, new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "you pick <" + items [which] + ">" );
}
});
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void multiChoice(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "multiple choice dialog" )
.setIcon(R.drawable. ic_launcher )
.setMultiChoiceItems( items ,
new boolean []{ false , true , false , true }, null );
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void customList(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "custom list dialog" )
.setIcon(R.drawable. ic_launcher )
.setAdapter( new ArrayAdapter<String>( this ,
R.layout. array_item , items ), null );
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void customView(View source)
{
TableLayout loginForm = (TableLayout) getLayoutInflater()
.inflate(R.layout. login , null );
new AlertDialog.Builder( this )
.setTitle( "custom view dialog" )
.setIcon(R.drawable. ic_launcher )
.setView(loginForm)
.setPositiveButton( "login" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// login operation
}
})
.setNegativeButton( "cancel" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// login operation
}
})
.create()
.show();
}
TextView show ;
String[] items = new String[] {
"疯狂Java讲义" , "疯狂Ajax讲义" ,
"轻量级Java EE企业应用实战" ,
"疯狂Android讲义" };
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
}
@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu. main , menu);
return true ;
}
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
if (id == R.id. action_settings ) {
return true ;
}
return super .onOptionsItemSelected(item);
}
public void simple(View source) {
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "simple alert dialog" )
.setIcon(R.drawable. ic_launcher )
.setMessage( "test content\n secon row content" );
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
private AlertDialog.Builder setPositiveButton(AlertDialog.Builder builder)
{
return builder.setPositiveButton( "Sure" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "clicked 'sure' button" );
}
});
}
private AlertDialog.Builder setNegativeButton(AlertDialog.Builder builder)
{
return builder.setNegativeButton( "Cancel" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "clicked 'cancel' button" );
}
});
}
public void simpleList(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "simple list dialog" )
.setIcon(R.drawable. ic_launcher )
.setItems( items , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "you pick <" + items [which] + ">" );
}
});
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void singleChoice(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "single choice dialog" )
.setIcon(R.drawable. ic_launcher )
.setSingleChoiceItems( items , 1, new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
show .setText( "you pick <" + items [which] + ">" );
}
});
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void multiChoice(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "multiple choice dialog" )
.setIcon(R.drawable. ic_launcher )
.setMultiChoiceItems( items ,
new boolean []{ false , true , false , true }, null );
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void customList(View source)
{
AlertDialog.Builder builder = new AlertDialog.Builder( this )
.setTitle( "custom list dialog" )
.setIcon(R.drawable. ic_launcher )
.setAdapter( new ArrayAdapter<String>( this ,
R.layout. array_item , items ), null );
setPositiveButton(builder);
setNegativeButton(builder).create().show();
}
public void customView(View source)
{
TableLayout loginForm = (TableLayout) getLayoutInflater()
.inflate(R.layout. login , null );
new AlertDialog.Builder( this )
.setTitle( "custom view dialog" )
.setIcon(R.drawable. ic_launcher )
.setView(loginForm)
.setPositiveButton( "login" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// login operation
}
})
.setNegativeButton( "cancel" , new OnClickListener()
{
@Override
public void onClick(DialogInterface dialog, int which)
{
// login operation
}
})
.create()
.show();
}
}
2.9.2 对话框风格的窗口
<activity
android:name=".DialogTheme"
android:theme="@android:style/Theme.Dialog"
android:label="@string/app_name">
<intent-filter>
<action android:name="android.intent.action.MAIN" />
<category android:name="android.intent.category.LAUNCHER" />
</intent-filter>
</activity>
2.9.3 PopupWindow
可以创建类似对话框风格的窗口,只需要如下两个步骤即可:
- 调用PopupWindow 的构造器创建PopupWindow对象
- 调用PopupWindow的showAsDropDown(View v) 将PopupWindow在指定位置显示出来
示例代码:
public
class
MainActivity
extends
ActionBarActivity {
@ Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
View root = this .getLayoutInflater().inflate(R.layout. popup , null );
final PopupWindow popup = new PopupWindow(root, 280, 360);
Button button = (Button) findViewById(R.id. bn );
button.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
popup.showAtLocation(findViewById(R.id. bn ), Gravity. CENTER , 20, 20);
}
});
root.findViewById(R.id. close ).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
popup.dismiss();
}
@ Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
View root = this .getLayoutInflater().inflate(R.layout. popup , null );
final PopupWindow popup = new PopupWindow(root, 280, 360);
Button button = (Button) findViewById(R.id. bn );
button.setOnClickListener( new OnClickListener()
{
@Override
public void onClick(View v)
{
popup.showAtLocation(findViewById(R.id. bn ), Gravity. CENTER , 20, 20);
}
});
root.findViewById(R.id. close ).setOnClickListener(
new View.OnClickListener() {
@Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
popup.dismiss();
}
});
}
}
2.9.4 DatPickerDialog、TimePickerDialog
使用这两种Dialog的步骤也较简单,只需要两个步骤即可:
- 通过new关键字创建实例,调用他们的show()即可显示对话框
- 为它们绑定监听器
示例代码:
public
class
MainActivity
extends
ActionBarActivity {
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
Button dateBn = (Button) findViewById(R.id. dateBn );
Button timeBn = (Button) findViewById(R.id. timeBn );
dateBn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View source) {
Calendar c = Calendar.getInstance();
new DatePickerDialog(MainActivity. this ,
new DatePickerDialog.OnDateSetListener() {
@Override
public void onDateSet(DatePicker dp, int year,
int month, int dayOfMonth) {
// TODO Auto-generated method stub
EditText show = (EditText) findViewById(R.id. show );
show.setText( "you've picked : " + year + "."
+ month + 1 + "." + dayOfMonth);
}
}
, c.get(Calendar. YEAR )
, c.get(Calendar. MONTH )
, c.get(Calendar. DAY_OF_MONTH )).show();
}
});
timeBn.setOnClickListener( new OnClickListener() {
@Override
public void onClick(View source) {
Calendar c = Calendar.getInstance();
new TimePickerDialog(MainActivity. this ,
new TimePickerDialog.OnTimeSetListener() {
@Override
public void onTimeSet(TimePicker tp, int hourOfDay,
int minute) {
// TODO Auto-generated method stub
EditText show = (EditText) findViewById(R.id. show );
show.setText( "you've picked : " + hourOfDay + ":"
+ minute );
}
}
, c.get(Calendar. HOUR_OF_DAY )
, c.get(Calendar. MINUTE )
, true ).show();
}
});
}
}
2.9.5 ProgressDialog
ProgressDialog代表了进度对话框,程序只要创建ProgressDialog实例,并将它显示出来就是一个进度对话框。有如下两种方式创建对话框:
- show()
- 设置后显示
设置的常用方法有:
setIndeterminate(boolean indeterminate)
|
设置对话框里的进度条不显示进度值
|
setMax(int max)
|
设置对话框里进度条的最大值
|
setMessage(CharSequence message)
|
设置对话框里显示的消息
|
setProgress(int value)
|
设置对话框里进度条里显示的消息
|
setProgressStyle(int style)
|
设置对话框里进度条的风格
|
示例代码:
public
class
MainActivity
extends
ActionBarActivity {
final static int MAX_PROGRESS = 100;
private int [] data = new int [50];
int progressStatus = 0;
int hasData = 0;
ProgressDialog pd1 , pd2 ;
Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg. what == 0x123)
{
pd2 .setProgress( progressStatus );
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
}
public void showSpinner(View source)
{
pd1 = new ProgressDialog(MainActivity. this );
pd1 .setTitle( "mission excuting" );
pd1 .setMessage( "please wait" );
pd1 .setCancelable( true );
pd1 .setProgressStyle(ProgressDialog. STYLE_HORIZONTAL );
pd1 .setIndeterminate( true );
pd1 .show();
}
public void showProgress(View source)
{
progressStatus = 0;
hasData = 0;
pd2 = new ProgressDialog(MainActivity. this );
pd2 .setMax( MAX_PROGRESS );
pd2 .setTitle( "mission completed percentage" );
pd2 .setMessage( "completed part" );
pd2 .setCancelable( false );
pd2 .setProgressStyle(ProgressDialog. STYLE_HORIZONTAL );
pd2 .setIndeterminate( true );
pd2 .show();
new Thread()
{
public void run()
{
while ( progressStatus < MAX_PROGRESS )
{
progressStatus = MAX_PROGRESS
* doWork() / data . length ;
handler .sendEmptyMessage(0x123);
}
if ( progressStatus >= MAX_PROGRESS )
{
pd2 .dismiss();
}
}
}.start();
}
public int doWork()
{
data [ hasData ++] = ( int ) (Math.random() * 100);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return hasData ;
}
final static int MAX_PROGRESS = 100;
private int [] data = new int [50];
int progressStatus = 0;
int hasData = 0;
ProgressDialog pd1 , pd2 ;
Handler handler = new Handler()
{
@Override
public void handleMessage(Message msg)
{
if (msg. what == 0x123)
{
pd2 .setProgress( progressStatus );
}
}
};
@Override
protected void onCreate(Bundle savedInstanceState) {
super .onCreate(savedInstanceState);
setContentView(R.layout. activity_main );
}
public void showSpinner(View source)
{
pd1 = new ProgressDialog(MainActivity. this );
pd1 .setTitle( "mission excuting" );
pd1 .setMessage( "please wait" );
pd1 .setCancelable( true );
pd1 .setProgressStyle(ProgressDialog. STYLE_HORIZONTAL );
pd1 .setIndeterminate( true );
pd1 .show();
}
public void showProgress(View source)
{
progressStatus = 0;
hasData = 0;
pd2 = new ProgressDialog(MainActivity. this );
pd2 .setMax( MAX_PROGRESS );
pd2 .setTitle( "mission completed percentage" );
pd2 .setMessage( "completed part" );
pd2 .setCancelable( false );
pd2 .setProgressStyle(ProgressDialog. STYLE_HORIZONTAL );
pd2 .setIndeterminate( true );
pd2 .show();
new Thread()
{
public void run()
{
while ( progressStatus < MAX_PROGRESS )
{
progressStatus = MAX_PROGRESS
* doWork() / data . length ;
handler .sendEmptyMessage(0x123);
}
if ( progressStatus >= MAX_PROGRESS )
{
pd2 .dismiss();
}
}
}.start();
}
public int doWork()
{
data [ hasData ++] = ( int ) (Math.random() * 100);
try
{
Thread.sleep(100);
}
catch (InterruptedException e)
{
e.printStackTrace();
}
return hasData ;
}
}
main.xml代码:
<
LinearLayout
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:orientation = "vertical"
android:gravity = "center_horizontal" >
< Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "progress status"
android:onClick = "showSpinner" />
< Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "hide status"
android:onClick = "showIndeterminate" />
< Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "show status"
android:onClick = "showProgress" />
xmlns:tools = "http://schemas.android.com/tools"
android:layout_width = "match_parent"
android:layout_height = "match_parent"
android:orientation = "vertical"
android:gravity = "center_horizontal" >
< Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "progress status"
android:onClick = "showSpinner" />
< Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "hide status"
android:onClick = "showIndeterminate" />
< Button
android:layout_width = "match_parent"
android:layout_height = "wrap_content"
android:text = "show status"
android:onClick = "showProgress" />
</
LinearLayout
>