This is my code:
public class CustomDialog extends DialogFragment {
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder myDialogBuilder = new AlertDialog.Builder(getActivity());
myDialogBuilder.setTitle("Get Ready To Rumble!");
myDialogBuilder.setMessage("Do you wanna rumble?!");
myDialogBuilder.setPositiveButton(
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(. this, "Let's Rumble!", Toast.LENGTH_SHORT).show();
}
}
)
return myDialogBuilder.create();
}
}
There seems to be an error of the content at the line :
Toast.makeText(CustomDialog.this, "Let's Rumble!", Toast.LENGTH_SHORT).show();
I've tried just typing "this", "DialogFragment.this"... Can't seem to find out the problem.
Hope you guys can help me, sorry for the long code.
答案 0 :(得分:0)
Use it like this
Toast.makeText(CustomDialog.this.getActivity(), "Let's Rumble!", Toast.LENGTH_SHORT).show();
答案 1 :(得分:0)
您可以使用此
Dialog mainDialog = (Dialog) dialog;
Context context = mainDialog.getContext();
答案 2 :(得分:0)
有几种方法可以完成这项工作 最简单的是调用它
Toast.makeText(getActivity(), "test", Toast.LENGTH_SHORT).show();
另一种方法是将上下文作为对话框构造函数参数传递给任何其他数据,但不要忘记创建默认的noarg以及
public class CustomDialog extends DialogFragment {
private Context context;
public CustomDialog(Context context){
this.context = context;
}
public CustomDialog(){}
//you may get a warning but it works
}
答案 3 :(得分:0)
使用getActivity()
处理片段时,会返回片段当前与之关联的活动。
如果您正在处理正常活动传递上下文或getApplicationContext()
没问题。
答案 4 :(得分:0)
您可以尝试这样做,只需在创建CustomDialog类对象时传递您的活动上下文:
public class CustomDialog extends DialogFragment {
private Context context;
public CustomDialog(Context context){
this.context = context;
}
public CustomDialog(){ } //default no arg constructor
@NonNull
@Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
AlertDialog.Builder myDialogBuilder = new AlertDialog.Builder(getActivity());
myDialogBuilder.setTitle("Get Ready To Rumble!");
myDialogBuilder.setMessage("Do you wanna rumble?!");
myDialogBuilder.setPositiveButton(
new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
Toast.makeText(context, "Let's Rumble!", Toast.LENGTH_SHORT).show();
}
}
)
return myDialogBuilder.create();
}