Android开发Android开发经验谈Android开发

在自定义Dialog中使用fragment后报not attac

2019-08-12  本文已影响11人  RubinTry
image.png
    从log中我们可以看到,此次异常最明显的关键词是fragment和context,那么我们来一一排除,首先,确保自定义的dialog传进来的context就是外部的activity(如果是fragment调用的dialog那就确保是getActivity()),要是在这样的情况下还是出现异常的话那么肯定是fragment的问题或者是fragment本身就和Dialog/AlertDialog不兼容。
    这时,我们把fragment相关的代码注释掉,发现并不会出现异常,那么我开始检查一下fragment的每一个使用步骤,这里我用的是tablayout + viewPager + fragment的方式,所以第一步我先检查fragmengManager,在这个dialog中,我用的fragmanager是从外部传进来的getChildFragmentManager(),于是乎,我把它替换成了activity里的getSupportFragmentManager(),照样闪退。无奈之下上网搜索了一下,没有一篇文章是跟Dialog或者AlertDialog这个类有直接关系的,大部分都是关于DialogFragment这个类的,偶然间我看到一篇文章Android 如何在Dialog中使用ViewPager,然后我尝试修改了一下代码,居然真的行了,太神了。
代码如下:
public class MyDialog extends DialogFragment {
    @BindView(R.id.tbStudentAccess)
    TabLayout tb;
    @BindView(R.id.viewPagerLessonAccess)
    ViewPager viewpager;
    private MyAdapter pagerAdapter;
    private List<String> titleList;
    private List<Fragment> fragmentList;
    private Context context;

    public MyDialog () {
    }

    @SuppressLint("ValidFragment")
    public MyDialog (Builder builder) {
        this.context = builder.context;
    }

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.dialog_layout, container , false);
        ButterKnife.bind(this , view);
        initViews();
        return view;
    }

    private void initViews() {
        fragmentList = new ArrayList<>();
        titleList = new ArrayList<>();
        titleList.add("item1");
        titleList.add("item2");
        fragmentList.add(new MyFragment1());
        fragmentList.add(new MyFragment2());
        pagerAdapter = new MyAdapter (getChildFragmentManager() , 1 , titleList , fragmentList);
        pagerAdapter.notifyDataSetChanged();
        viewpager.setOffscreenPageLimit(2);
        viewpager.setAdapter(pagerAdapter);
        tb.setupWithViewPager(viewpager);
        viewpager.addOnPageChangeListener(new TabLayout.TabLayoutOnPageChangeListener(tbStudentAccess));
        tb.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
            @Override
            public void onTabSelected(TabLayout.Tab tab) {
                viewPagerLessonAccess.setCurrentItem(tab.getPosition());
            }

            @Override
            public void onTabUnselected(TabLayout.Tab tab) {

            }

            @Override
            public void onTabReselected(TabLayout.Tab tab) {

            }
        });
    }

    @Override
    public void onStart() {
        super.onStart();
        Window window = getDialog().getWindow();
        if (window != null) {
            // 一定要设置Background,如果不设置,window属性设置无效,这条语句也可用来设置根布局的颜色和形状
            window.setBackgroundDrawable(ContextCompat.getDrawable(context , R.drawable.shape_lesson_access_student_dialog));
            DisplayMetrics dm = new DisplayMetrics();
            if (getActivity() != null) {
                WindowManager windowManager = getActivity().getWindowManager();
                if (windowManager != null) {
                    windowManager.getDefaultDisplay().getMetrics(dm);
                    WindowManager.LayoutParams params = window.getAttributes();
                    params.gravity = Gravity.CENTER;
                    // 使用ViewGroup.LayoutParams,以便Dialog 宽度充满整个屏幕
                    params.width = ScreenUtils.getScreenWidth() - SizeUtils.dp2px(40);
                    params.height = ViewGroup.LayoutParams.WRAP_CONTENT;
                    window.setAttributes(params);
                }
            }
        }
        
    }

    

    public static class Builder{
        private Context context;
        private String studentName;
        private DialogInterface.OnCancelListener onCancelListener;
        public Builder(Context context) {
            this.context = context;
        }

        public Builder setStudentName(String studentName) {
            this.studentName = studentName;
            return this;
        }

        public Builder setOnCancelListener(DialogInterface.OnCancelListener onCancelListener) {
            this.onCancelListener = onCancelListener;
            return this;
        }
        

        public MyDialog build(){
            if(TextUtils.isEmpty(studentName)){
                throw new IllegalArgumentException("studentName is null");
            }
            return new MyDialog (this);
        }
    }
}
上一篇下一篇

猜你喜欢

热点阅读