我想在创建片段后立即显示AlertDialog(带有几个单选按钮按钮和一个OK按钮)。
调用对话框片段的最佳位置在哪里?我已经尝试过onViewCreated()和onResume(),但两者都有效,但我不确定最佳实践。
另外,为了确保每次片段停止/重新创建时都没有显示对话框,例如,由于屏幕旋转,我创建了名为mShowDialog的布尔值,并将其设置为' true&#39 ;在onCreate()然后使用' If'决定是否应显示对话框的陈述(见下文)。
onCreate(){
//....
mShowDialog = true;
}
onResume(){
if (mShowDialog){
//....show dialog code
// set mShowDialog to false to ensure code executed only once
mShowDialog = false;
}
}
上述代码是否是满足这两个要求的最佳方式?
不过,我对编程很新。提前感谢您的帮助。
答案 0 :(得分:1)
最佳做法是在onCreateView()
片段方法中膨胀对话框。
答案 1 :(得分:0)
如果您尝试通过添加片段的活动创建它,我很幸运能够在片段中添加FragmentListener
并从活动中设置它。这是我所有片段扩展的基本BaseFragment
类:
public class BaseFragment extends Fragment {
public Context context;
public Activity activity;
public FragmentListener fragmentListener;
private boolean attached = false;
public BaseFragment() {
}
@Override
public void onAttach(Activity activity) {
super.onAttach(activity);
if (!isAttached()) {
this.context = activity;
this.activity = activity;
if (this.fragmentListener != null) {
this.fragmentListener.onAttached();
}
setAttached(true);
}
}
@Override
public void onAttach(Context context) {
super.onAttach(context);
if (!isAttached()) {
this.context = context;
this.activity = (Activity) context;
if (this.fragmentListener != null) {
this.fragmentListener.onAttached();
}
setAttached(true);
}
}
@Override
public void onDetach() {
super.onDetach();
setAttached(false);
if (this.fragmentListener != null){
this.fragmentListener.onDetached();
}
}
public void setFragmentListener(FragmentListener fragmentListener) {
this.fragmentListener = fragmentListener;
}
public View.OnClickListener onBackTapped = new View.OnClickListener() {
@Override
public void onClick(View v) {
getActivity().onBackPressed();
}
};
public boolean isAttached() {
return attached;
}
public void setAttached(boolean attached) {
this.attached = attached;
}
public boolean isPermissionGranted(String permission){
return ContextCompat.checkSelfPermission(context, permission) == PackageManager.PERMISSION_GRANTED;
}
public boolean ifShouldShowRationaleForPermission(String permission){
return ActivityCompat.shouldShowRequestPermissionRationale(activity, permission);
}
public void showPermissionRequest(Activity activity, int requestCode, String... permissions){
ActivityCompat.requestPermissions(activity, permissions, requestCode);
}
}
这样,我可以在我的活动中这样做:
MyFragment myFragment = new MyFragment();
myfragment.setFragmentListener(new FragmentListener() {
@Override
public void onAttached() {
// Stuff I want to do when it is attached
}
@Override
public void onDetached() {
// Stuff I want to do when it is detached
}
});
fragmentManager.beginTransaction()
.add(R.id.container, myFragment)
.commit();
然后我可以添加我想要的任何代码,当片段做各种各样的事情。
祝你好运!