【问题标题】:No adapter attached; skipping layout, Only displays 1st time each Fragment (Tablayout)未连接适配器;跳过布局,每个 Fragment 仅显示第 1 次(Tablayout)
【发布时间】:2018-05-01 13:37:21
【问题描述】:

我正在使用带有 RecyclerView 的片段的选项卡布局。如果我只使用一个或 2 个选项卡,这是一个问题,它可以正常工作。 但是如果我超过了 2 个标签,它在第一次加载布局时,但如果我开始在标签之间切换,内容就会消失,并在 logcat 中显示一条消息“未连接适配器;跳过布局”,您可以看到起初它在 tab1 和 tab3 消失后工作正常。 找了很久,有很多问题,但我觉得我的情况不一样,如果我的代码有问题,那么它不应该第一次加载,我也想在这里提一下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);
        }
    }





}

【问题讨论】:

  • 我们可以查看您遇到该问题的片段的一些代码吗?
  • 兄弟它的片段代码..除了变量posType..之外的所有片段都相同。
  • 连接适配器onTabChange(),当null? FragmentTabHost 的代码相当相关 - 虽然这是 Fragment,但不完全是“标签”(名称的选择非常误导)。但是,TabHost 可能会干扰,因为我在 FragmentTabHost 中有几十个 RecyclerView 并且它可以正常工作。
  • 兄弟我已经编辑了我的问题,现在请看一下..

标签: firebase android-fragments android-recyclerview adapter


【解决方案1】:

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-05-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-04-15
    • 2021-04-24
    相关资源
    最近更新 更多