不确定该标题如何描述我希望做的事情,但在这里。基本上我有一个应用程序,它实用地创建一个按钮列表,当点击它时返回一个描述。
我创建了以下课程
public class DynamicOnClickListener implements OnClickListener
{
String description;
public DynamicOnClickListener(String adesc) {
//sets the description attribute at instantiation
this.description = adesc;
}
public void onClick(View v) {
//on button click returns dialog box with description in it
Log.v("DynamicOnClickListener","1");
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
builder.setMessage(description);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}
这可以完美地工作,但是我非常想在某种程度上使对话框更加活跃。我一直在网上查看一些示例,根据 android 文档,他们建议定义自定义 xml 布局并使用 LayourInflator 将自定义 xml 设置为对话框的视图。(好吧,反正我就是这么理解的,可能是错误的就够了)
尽管文档示例与我的示例略有不同,但根据他们的示例,我应该添加以下几行
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.dialog_signin, null))
但是,当我将它添加到我的班级时,导致以下我在 getActivity() 上收到错误
public class DynamicOnClickListener implements OnClickListener
{
String description;
public DynamicOnClickListener(String adesc) {
//sets the description attribute at instantiation
this.description = adesc;
}
public void onClick(View v) {
//on button click returns dialog box with program description in it
Log.v("DynamicOnClickListener","1");
AlertDialog.Builder builder = new AlertDialog.Builder(v.getContext());
// Get the layout inflater
LayoutInflater inflater = getActivity().getLayoutInflater();
// Inflate and set the layout for the dialog
// Pass null as the parent view because its going in the dialog layout
builder.setView(inflater.inflate(R.layout.description_dialog, null));
builder.setMessage(description);
builder.setCancelable(false);
builder.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int id)
{
dialog.cancel();
}
});
AlertDialog alert = builder.create();
alert.show();
}
}