我正在尝试在点击操作栏的项目时显示AlertDialog,但没有任何反应!我是Android编程新手所以你能给我发一些代码或者告诉我怎么做吗?
感谢所有人!!
Matteo
答案 0 :(得分:3)
好的,首先点击动作栏的项目时,你必须抓住事件吗?
@Override
public boolean onOptionsItemSelected(MenuItem item)
{
if (item.getItemId() == android.R.id.home) //the androi.r.id.home have to changed
//for the id of your button.
{
///here is where you have to show the alertdialog!!!!
}
}
public boolean onOptionsItemSelected(MenuItem item)
{
//This is the layout that you are going to use in your alertdialog
final View addView = getLayoutInflater().inflate(R.layout.add, null);
new AlertDialog.Builder(this).setTitle("Add a Word").setView(addView)
.setPositiveButton("OK", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int whichButton) {
addWord((TextView) addView.findViewById(R.id.title));
}
}).setNegativeButton("Cancel", null).show();
return (super.onOptionsItemSelected(item));
}
在这里获取完整的源表格..
http://vimaltuts.com/android-tutorial-for-beginners/android-action-bar-tab-menu-example
你也可以这样构建你的AlertDialgog:
new AlertDialog.Builder(this)
.setTitle("Delete entry")
.setMessage("Are you sure you want to delete this entry?")
.setPositiveButton(android.R.string.yes, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// continue with delete
}
})
.setNegativeButton(android.R.string.no, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
// do nothing
}
})
.setIcon(android.R.drawable.ic_dialog_alert)
.show();
答案 1 :(得分:2)
显示您的代码。示例可能是这样的:
@Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar actions click
switch (item.getItemId()) {
case R.id.itemid:
new AlertDialog.Builder(this)
.setMessage("Message")
.setCancelable(false)
.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id) {
//code if yes
}
})
.setNegativeButton("No", null)
.show();
return true;
default:
return super.onOptionsItemSelected(item);
}
}