我正在寻找一个简单的弹出菜单,可用于在 2.3.3 及更高版本上运行的手机。
像这样的东西,与 ContextMenu 的工作方式不同,因为它不需要列表视图:
尝试以下操作:
在布局文件夹中创建一个文件 dialog.xml 并添加以下代码:
<?xml version="1.0" encoding="utf-8"?>
<TextView
android:id="@+id/ErrorMsg"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="10dp"
android:text="Do you want to un-install this app?" />
<LinearLayout
android:layout_below="@+id/ErrorMsgDialog"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal" >
<Button android:id="@+id/Cancel"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text="Cancel" />
<Button android:id="@+id/Ok"
android:layout_width="0dp"
android:layout_height="wrap_content"
android:layout_weight="1"
android:textSize="15sp"
android:text="OK" />
</LinearLayout>
然后在您的类文件中使用以下代码显示对话框:
AlertDialog.Builder builder = new AlertDialog.Builder(context);
View view = LayoutInflater.from(context).inflate(
R.layout.dialog, null);
builder.setView(view);
dialog = builder.create();
dialog.setCanceledOnTouchOutside(true);
Button cancel = (Button) view.findViewById(R.id.Cancel);
cancel.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
dialog.dismiss();
}
});
Button ok = (Button) view.findViewById(R.id.Ok);
ok.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// Do something here for OK action
}
});
dialog.show();
最简单的方法是创建一个 AlertDialog.Builder 对象并配置其正面和负面按钮,然后设置标题和消息并完成。不再需要任何布局文件。