我想要创建一个有3个选项的弹出窗口。 (阻止,取消阻止,卸载)。下面我有一个确认|取消按钮。我想看看哪个按钮被按下,并根据它将显示与选择对应的吐司。我写了一些代码来展示我想要做的事情。显然,if items [item] == Block将不起作用,但在简化的意义上,这正是我想要做的。有人可以告诉我如何编写OnClickListener以捕获单击的按钮以及单击确认时如何区分它?
代码:
package com.popup;
import android.app.Activity;
import android.app.AlertDialog;
import android.content.DialogInterface;
import android.os.Bundle;
import android.util.Log;
import android.widget.Toast;
public class PopupActivity extends Activity {
String TAG = "PopUpActivity";
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
BlockUnblockUninstallPopUp("");
String TAG = "PopUpActivity";
}
public void BlockUnblockUninstallPopUp(final String PackageName){
//Items you would like to list as options.
final CharSequence[] items = {"Block", "UnBlock", "Uninstall"};
String flag = null;
AlertDialog.Builder builder = new AlertDialog.Builder(PopupActivity.this);
//Title of Popup
builder.setTitle("What would you like to do?");
builder.setSingleChoiceItems(items, -1, new DialogInterface.OnClickListener() {
//When you click the radio button
public void onClick(DialogInterface dialog, int item) {
}
});
//When you click Confirm
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if(items[item] == "Block")
{
Toast.makeText(PopupActivity.this,PackageName + " Blocked.", Toast.LENGTH_SHORT).show();
Log.d(TAG,PackageName + " Blocked.");
}
if(items[item] == "Unblock")
{
Toast.makeText(PopupActivity.this,PackageName + " Unblocked.", Toast.LENGTH_SHORT).show();
Log.d(TAG,PackageName + " Unblocked.");
}
if(items[item] == "Uninstall")
{
Toast.makeText(PopupActivity.this,PackageName + " Uninstalled.", Toast.LENGTH_SHORT).show();
Log.d(TAG,PackageName + " Uninstalled.");
}
}
});
//When you click Cancel, Leaves PopUp.
builder.setNegativeButton("Cancel",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
}
});
//Creates the AlertDialog
AlertDialog alert = builder.create();
//Starts the Popup.
alert.show();
}
}
答案 0 :(得分:5)
int i;
builder.setSingleChoiceItems(items, -1,
new DialogInterface.OnClickListener() {
// When you click the radio button
public void onClick(DialogInterface dialog, int item) {
i=item;
}
});
builder.setPositiveButton("Confirm",
new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item) {
if (items[i] == "Block") {
Toast.makeText(PopupActivity.this,
PackageName + " Blocked.",
Toast.LENGTH_SHORT).show();
Log.d(TAG, PackageName + " Blocked.");
}
if (items[i] == "UnBlock") {
Toast.makeText(PopupActivity.this,
PackageName + " Unblocked.",
Toast.LENGTH_SHORT).show();
Log.d(TAG, PackageName + " Unblocked.");
}
if (items[i] == "Uninstall") {
Toast.makeText(PopupActivity.this,
PackageName + " Uninstalled.",
Toast.LENGTH_SHORT).show();
Log.d(TAG, PackageName + " Uninstalled.");
}
}
});