好吧,所以我希望有一个自定义对话框,但我无法弄清楚如何在调用该函数时使它出现。
public void addHomework() {
final Dialog alert = new Dialog(this);
alert.setTitle("Add Homework");
alert.setContentView(R.layout.homework_item_entry);
Button add_button = (Button) findViewById(R.id.add_homework_button);
Button cancel_button = (Button) findViewById(R.id.cancel_homework_button);
add_button.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
Toast.makeText(ClassHomeworkList.this, "Adding homework", Toast.LENGTH_SHORT).show();
}
});
cancel_button.setOnClickListener( new OnClickListener() {
public void onClick(View v) {
alert.dismiss();
}
});
alert.show();
}
我该怎么办?
答案 0 :(得分:4)
我知道这是一个老线程,但即使在阅读了Android文档后,对我来说如何使用标准Dialog类显示自定义对话框也不明显。基本上你可以打电话:
this.showDialog(MANAGE_PASSWORD); // MANAGE_PASSWORD static final int
来自您的活动。然后在onCreateDialog方法中实例化自定义对话框:
protected Dialog onCreateDialog(int id) {
Dialog dialog;
switch(id) {
case MANAGE_PASSWORD:
dialog= getInstancePasswordDialog();
break;
case DIALOG_ABOUT:
// do the work to define the About Dialog
dialog= getInstanceAlertDialog(); // called "the first time"
break;
default:
dialog = null;
}
return dialog;
}
实例化对话框的代码位于getInstancePasswordDialog()中。这是code sample。
答案 1 :(得分:1)
我认为你的问题是你的ID无法找到你的两个按钮(因为你试图在你的主要活动中找到它们,但它们在对话框的布局中)
Button add_button = (Button) findViewById(R.id.add_homework_button);
Button cancel_button = (Button) findViewById(R.id.cancel_homework_button);
但需要这样做:
Button add_button = (Button) alert.findViewById(R.id.add_homework_button);
Button cancel_button = (Button) alert.findViewById(R.id.cancel_homework_button);
答案 2 :(得分:0)
LayoutInflater factory = LayoutInflater.from(this);
View view = factory.inflate(R.layout.dialog, null);
//the id is your root layout
LinearLayout layout = (LinearLayout) view.findViewById(R.id.layout);
alert.setContentView(layout);
答案 3 :(得分:0)
您是否阅读了以下文件:http://developer.android.com/guide/topics/ui/dialogs.html#ShowingADialog?
您应该覆盖Activity中的onCreateDialog(int)方法,然后使用showDialog(int)