对于开发的提示消息大家可能都不陌生,就是在点击某些按钮之后,会给用户一个反馈信息,这个就是提示消息的功能,良好的提示消息可以给用户一个良好的用户体验,所以我们今天的学习目标就是正确的使用提示框AlertDialog。
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.view.View;
import android.widget.Button;
public class DialogDemoActivity extends Activity {
private Button button;
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dialog);
button = (Button) findViewById(R.id.button1);
button.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View arg0) {
AlertDialog.Builder builder = new AlertDialog.Builder(
DialogDemoActivity.this);
builder.setTitle("Message")
.setMessage("你确定要上网么?")
.setCancelable(false)
.setPositiveButton("确定",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
Intent intent = new Intent(
Intent.ACTION_VIEW,
Uri.parse("http://www.haosou.com"));
startActivity(intent);
}
})
.setNegativeButton("取消",
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog,
int id) {
dialog.cancel();
}
});
AlertDialog dialog = builder.create();
dialog.show();
}
});
}
}
通过以上代码即可以实现基本的提示消息,下面我们对上面的功能进行详细的讲解。
AlertDialog.Builder builder=new AlertDialog.Builder(XxxActivity.this);
这是创建一个AlertDialog类的内部类的Builder的对象,主要功能参数配置都需要这个类来实现,常用的方法有以下几个方法。
builder.setTitle("Message");
此方法是用来设置提示消息的标题。
builder.setMessage("你确定要上网么?");
此方法是设置提示消息的具体内容。
builder.setCancelable(false);
此方法是设置键盘上的后退按钮是否生效,设置fasle后后退按钮失效,设置true后后退按钮生效。
builder.setPositiveButton("确定",事件);
添加确定按钮,并添加对该按钮的处理事件。
builder.setNegativeButton("取消",事件);
添加取消按钮,并添加对该按钮的处理事件。
通过以上的方法就可以灵活设置你想要的提示消息了,但是提示消息的显示效果可能不是很理想,是默认的效果,没有特别好的效果,如果你想拥有好的效果,那你就需要进行相应的样式设置。