没有适配器;跳过布局,仅显示第一次每个片段(Tablayout)

时间:2018-05-01 13:37:22

标签: firebase android-fragments android-recyclerview adapter

我正在使用使用RecyclerView片段的标签布局。这是一个问题,如果我只使用一个或两个选项卡它可以正常工作。 但是,如果我超过2个选项卡,第一次加载布局但如果我开始在选项卡之间切换内容已经消失了logcat中的消息“没有适配器附加;跳过布局”,你可以看到一开始它在tab1和tab3离开之后工作正常.. enter image description here 我一直在寻找它,有很多关于这个的问题,但我认为我的情况有所不同,如果我的代码有问题那么它不应该第一次加载,我也想在这里提一下posType是我的可靠的,对于所有标签,其他代码是相同的。适配器连接到firebase并为不同的变量选择不同的内容。对不起,我是初学者,指导我的错误或不好的解释。这是我的代码。

public class Tab4Fragment extends android.support.v4.app.Fragment {


    @Nullable
    @Override
    public View onCreateView( @NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.tab4_fragment, container, false);

        posType = "Quiz";


        profileManager = ProfileManager.getInstance(getActivity());

        postManager = PostManager.getInstance(getActivity());


        floatingActionButton = (FloatingActionButton) view.findViewById(R.id.addNewPostFab);
        if (recyclerView == null) {

            if (floatingActionButton != null) {
                floatingActionButton.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick( View v ) {
                        if (hasInternetConnection()) {
                            addPostClickAction();
                        } else {
                            showFloatButtonRelatedSnackBar(R.string.internet_connection_failed);
                        }
                    }
                });
            }

            newPostsCounterTextView = (TextView) view.findViewById(R.id.newPostsCounterTextView);
            newPostsCounterTextView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick( View v ) {
                    refreshPostList((posType));
                }
            });

            final ProgressBar progressBar = (ProgressBar) view.findViewById(R.id.progressBar);
            SwipeRefreshLayout swipeContainer = (SwipeRefreshLayout) view.findViewById(R.id.swipeContainer);
            recyclerView = (RecyclerView) view.findViewById(R.id.recycler_view);
            postsAdapter = new PostsAdapter((MainActivity) getActivity(), swipeContainer, "Quiz");
            postsAdapter.setCallback(new PostsAdapter.Callback() {
                @Override
                public void onItemClick( final Post post, final View view ) {
                    PostManager.getInstance(getActivity()).isPostExistSingleValue(post.getId(), new OnObjectExistListener<Post>() {
                        @Override
                        public void onDataChanged( boolean exist ) {
                            if (exist) {
                                openPostDetailsActivity(post, view);
                            } else {
                                showFloatButtonRelatedSnackBar(R.string.error_post_was_removed);
                            }
                        }
                    },posType);
                }

                @Override
                public void onListLoadingFinished() {
                    progressBar.setVisibility(View.GONE);
                }

                @Override
                public void onAuthorClick( String authorId, View view ) {
                    openProfileActivity(authorId, view);
                }

                @Override
                public void onCanceled( String message ) {
                    progressBar.setVisibility(View.GONE);
                    Toast.makeText(getActivity(), message, Toast.LENGTH_LONG).show();
                }
            });

            recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
            ((SimpleItemAnimator) recyclerView.getItemAnimator()).setSupportsChangeAnimations(false);
            recyclerView.setAdapter(postsAdapter);
            postsAdapter.loadFirstPage((posType));
            updateNewPostCounter();


            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled( RecyclerView recyclerView, int dx, int dy ) {
                    hideCounterView();
                    super.onScrolled(recyclerView, dx, dy);
                }
            });
        }



        postCounterWatcher = new PostManager.PostCounterWatcher() {
            @Override
            public void onPostCounterChanged( int newValue ) {
                updateNewPostCounter();
            }
        };

        postManager.setPostCounterWatcher(postCounterWatcher);  

        return view;

    }



    @Override
    public void onActivityResult( int requestCode, int resultCode, Intent data ) {
        super.onActivityResult(requestCode, resultCode, data);

        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case ProfileActivity.CREATE_POST_FROM_PROFILE_REQUEST:
                    refreshPostList((posType));
                    break;
                case CreatePostActivity.CREATE_NEW_POST_REQUEST:
                    refreshPostList((posType));
                    showFloatButtonRelatedSnackBar(R.string.message_post_was_created);
                    break;

                case PostDetailsActivity.UPDATE_POST_REQUEST:
                    if (data != null) {
                        PostStatus postStatus = (PostStatus) data.getSerializableExtra(PostDetailsActivity.POST_STATUS_EXTRA_KEY);
                        if (postStatus.equals(PostStatus.REMOVED)) {
                            postsAdapter.removeSelectedPost();
                            showFloatButtonRelatedSnackBar(R.string.message_post_was_removed);
                        } else if (postStatus.equals(PostStatus.UPDATED)) {
                            postsAdapter.updateSelectedPost((posType));
                        }
                    }
                    break;
            }
        }
    }



    @Override
    public void onResume() {
        super.onResume();
        updateNewPostCounter();

    }




    private void updateNewPostCounter() {
        Handler mainHandler = new Handler(getActivity().getMainLooper());
        mainHandler.post(new Runnable() {
            @Override
            public void run() {
                int newPostsQuantity = postManager.getNewPostsCounter();

                if (newPostsCounterTextView != null) {
                    if (newPostsQuantity > 0) {
                        showCounterView();

                        String counterFormat = getResources().getQuantityString(R.plurals.new_posts_counter_format, newPostsQuantity, newPostsQuantity);
                        newPostsCounterTextView.setText(String.format(counterFormat, newPostsQuantity));
                    } else {
                        hideCounterView();
                    }
                }
            }
        });
    }



    public void doAuthorization(ProfileStatus status) {
        if (status.equals(ProfileStatus.NOT_AUTHORIZED) || status.equals(ProfileStatus.NO_PROFILE)) {
            startLoginActivity();
        }
    }


    private void startLoginActivity() {
        Intent intent = new Intent(getActivity(), LoginActivity.class);
        startActivity(intent);
    }

    private void openCreatePostActivity() {
        Intent intent = new Intent(getActivity(), CreatePostActivity.class);
        intent.putExtra("posType", posType);
        startActivityForResult(intent, CreatePostActivity.CREATE_NEW_POST_REQUEST);
    }

    private void addPostClickAction() {
        ProfileStatus profileStatus = profileManager.checkProfile();

        if (profileStatus.equals(ProfileStatus.PROFILE_CREATED)) {
            openCreatePostActivity();
        } else {
            doAuthorization(profileStatus);
        }
    }

    public void showSnackBar(View view, int messageId) {
        Snackbar.make(getView().findViewById(R.id.main_content),
                messageId, Snackbar.LENGTH_LONG).show();

    }


    public void showSnackBar(String message) {

        Snackbar.make(getView().findViewById(R.id.main_content),
                message, Snackbar.LENGTH_LONG).show();

    }

    public void showSnackBar(int messageId) {

        Snackbar.make(getView().findViewById(R.id.main_content),
                messageId, Snackbar.LENGTH_LONG).show();
    }



    public void showFloatButtonRelatedSnackBar( int messageId ) {
        showSnackBar(floatingActionButton, messageId);

    }

    private void hideCounterView() {
        if (!counterAnimationInProgress && newPostsCounterTextView.getVisibility() == View.VISIBLE) {
            counterAnimationInProgress = true;
            AlphaAnimation alphaAnimation = AnimationUtils.hideViewByAlpha(newPostsCounterTextView);
            alphaAnimation.setAnimationListener(new Animation.AnimationListener() {
                @Override
                public void onAnimationStart( Animation animation ) {

                }

                @Override
                public void onAnimationEnd( Animation animation ) {
                    counterAnimationInProgress = false;
                    newPostsCounterTextView.setVisibility(View.GONE);
                }

                @Override
                public void onAnimationRepeat( Animation animation ) {

                }
            });

            alphaAnimation.start();
        }
    }
    private void openPostDetailsActivity( Post post, View v ) {
        Intent intent = new Intent(getActivity(), PostDetailsActivity.class);
        intent.putExtra("posType", posType);
        intent.putExtra(PostDetailsActivity.POST_ID_EXTRA_KEY, post.getId());

        if ((new String(posType).equals("Question")) || (new String(posType).equals("Quiz"))){
            startActivityForResult(intent, PostDetailsActivity.UPDATE_POST_REQUEST);
        } else {

            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {

                View imageView = v.findViewById(R.id.postImageView);
                View authorImageView = v.findViewById(R.id.authorImageView);

                ActivityOptions options = ActivityOptions.
                        makeSceneTransitionAnimation(getActivity(),
                                new android.util.Pair<>(imageView, getString(R.string.post_image_transition_name)),
                                new android.util.Pair<>(authorImageView, getString(R.string.post_author_image_transition_name))
                        );
                startActivityForResult(intent, PostDetailsActivity.UPDATE_POST_REQUEST, options.toBundle());
            } else {
                startActivityForResult(intent, PostDetailsActivity.UPDATE_POST_REQUEST);
            }
        }
    }


    public boolean hasInternetConnection() {
        ConnectivityManager cm = (ConnectivityManager) getActivity().getSystemService(Context.CONNECTIVITY_SERVICE);
        NetworkInfo activeNetwork = cm.getActiveNetworkInfo();
        return activeNetwork != null && activeNetwork.isConnectedOrConnecting();
    }



    @SuppressLint("RestrictedApi")
    private void openProfileActivity( String userId, View view ) {
        Intent intent = new Intent(getActivity(), ProfileActivity.class);
        intent.putExtra(ProfileActivity.USER_ID_EXTRA_KEY, userId);

        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP && view != null) {

            View authorImageView = view.findViewById(R.id.authorImageView);

            ActivityOptions options = ActivityOptions.
                    makeSceneTransitionAnimation(getActivity(),
                            new android.util.Pair<>(authorImageView, getString(R.string.post_author_image_transition_name)));
            startActivityForResult(intent, ProfileActivity.CREATE_POST_FROM_PROFILE_REQUEST, options.toBundle());
        } else {
            startActivityForResult(intent, ProfileActivity.CREATE_POST_FROM_PROFILE_REQUEST);
        }
    }


    private void showCounterView() {
        AnimationUtils.showViewByScaleAndVisibility(newPostsCounterTextView);
    }





    private void refreshPostList(String posType) {
        postsAdapter.loadFirstPage((posType));
        if (postsAdapter.getItemCount() > 0) {
            recyclerView.scrollToPosition(0);
        }
    }





}

1 个答案:

答案 0 :(得分:0)

经过长时间的研究后,我通过在MainActivity mViewPager.setOffscreenPageLimit(n);中添加此问题解决了我的问题,其中n是标签数量