我尝试在Fragment中构建一个AlertDialog但是找不到AlertDialog Builder的正确Context。
public class LoginFragment extends Fragment {
public LoginFragment() {
// Required empty public constructor
}
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_login, container, false);
Button btnEnter = (Button) rootView.findViewById(R.id.btnEnter);
// Listening to register new account link
btnEnter.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
// if play name already exists
AlertDialog dialog = new AlertDialog.Builder(getActivity())
.setCancelable(false)
.setIcon(R.drawable.login_icon)
.setMessage("Player Name Already Exists. Please Find a New Name.")
.setButton("Okay", new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
}).show();
}
});
return rootView;
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
}
@Override
public void onDetach() {
super.onDetach();
}
}
在这一行:
AlertDialog dialog = new AlertDialog.Builder(getActivity());
getActivity()无效。它说“需要AlertDialog,发现AlertDialog.Builder”。我尝试过像this.getActivity()和getContext()以及getSupportFragmentManager()这样的东西,所有这些都不起作用。我对此有点困惑。有人能告诉我应该使用哪些以及为什么?
答案 0 :(得分:3)
AlertDialog dialog = new AlertDialog.Builder(getActivity());
应替换为
AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
答案 1 :(得分:0)
这是一个自定义对话框,只需按照您的喜好进行编辑即可。
在片段内使用对话框的示例:
AlertDialog.Builder makeDialog = new AlertDialog.Builder(getActivity());
LayoutInflater li = getLayoutInflater(null);
View viewAdd = li.inflate(R.layout.random_dialog, null);
makeDialog.setView(viewAdd);
//editexts,textviews and that stuff goes here
makeDialog.setPositiveButton("Save", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
}
});
makeDialog.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
@Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
AlertDialog ad = makeDialog.create();
ad.show();