问题
需要向用户显示一个简单的弹出式对话框来进行事件通知或者展示一个选项列表实现原理
在向用户快速展示重要模块的场景中,AlertDialog是最搞效的解决方案。Android系统中提供了一个方便的AlertDialog.Builder类来快速实现效果
实现代码如下
package com.example.ho.alertdialogdemo;
import android.content.DialogInterface;
import android.support.v7.app.AlertDialog;
import android.support.v7.app.AppCompatActivity;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class MainActivity extends AppCompatActivity {
private static final String[] ITEMS = {"item1","item2","item3","item4","item5"};
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
final Button button = new Button(this);
button.setText("Click for");
setContentView(button);
final AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("select item");
builder.setItems(ITEMS, new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
String selected = ITEMS[i];
button.setText(selected);
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialogInterface, int i) {
// builder.di
}
});
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
builder.show();
}
});
}
}
本文介绍如何使用Android中的AlertDialog来创建一个简单的弹出对话框,用于事件通知或展示选项列表。通过具体的代码示例展示了如何设置标题、选项列表及按钮,并响应用户的点击事件。
199

被折叠的 条评论
为什么被折叠?



