我为用户提供了一个功能,可以拨打电话号码,退出应用程序并打开拨号程序。
直到这里,一切都好。但是现在我想在用户点击按钮时添加一个确认对话框,警告他调用将退出应用程序。 (“呼叫将退出应用程序。你确定吗?确认| Canel”)
我环顾四周但没有找到任何明确的例子。任何帮助将不胜感激,这是我迄今为止所拥有的。final String phoneNumber;
phoneNumber = "5555555555";
ImageButton callButton = (ImageButton)findViewById(R.id.btnCall);
callButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+phoneNumber));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("Calling a Phone Number", "Call failed", activityException);
}
}
});
答案 0 :(得分:4)
这应该做你想要的:
callButton.setOnClickListener(new OnClickListener(){
public void onClick(View v) {
OnClickListener listener = new OnClickListener(){
@Override
public void onClick(DialogInterface dialog, int which) {
if(which == Dialog.BUTTON_POSITIVE)
{
try {
Intent callIntent = new Intent(Intent.ACTION_DIAL);
callIntent.setData(Uri.parse("tel:"+phoneNumber));
startActivity(callIntent);
} catch (ActivityNotFoundException activityException) {
Log.e("Calling a Phone Number", "Call failed", activityException);
}
}
}
};
new AlertDialog.Builder(v.getContext())
.setMessage("Are you sure you want to leave the application?")
.setPositiveButton("Yes", listener)
.setNegativeButton("No", listener)
.show();
}
}
编辑用v.getContext()
替换上下文答案 1 :(得分:2)
您可以使用带有“是”和“否”按钮的“警报”对话框:
AlertDialog.Builder alert = new AlertDialog.Builder(this);
alert.setTitle("Title");
alert.setMessage("Message");
// Set an EditText view to get user input
final EditText input = new EditText(this);
alert.setView(input);
alert.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
String value = input.getText();
// Do something with value!
}
});
alert.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
// Canceled.
}
});
alert.show();
您可以在{/ 1}}之后在try / catch中插入此内容。
答案 2 :(得分:1)
您应该使用AlertDialog.Builder:http://developer.android.com/guide/topics/ui/dialogs.html#AlertDialog