分页不适用于交错网格布局android

Posted

技术标签:

【中文标题】分页不适用于交错网格布局android【英文标题】:Pagination not working with staggered grid layout android 【发布时间】:2021-09-22 07:45:56 【问题描述】:

您好,我试图在我的 recylerview 中包含分页,但不知道为什么它不能使用 staggeredgrid layout this the question im searching for 并且因为答案是针对 linearlayoutmanager 我得到了一个关于如何在 staggerdgrid layoutmanager here is the answer i tried in my code 中实现分页的答案,图像没有加载

ScreenShot // 我现在得到的 ss

短代码

int pastVisiblesItems, visibleItemCount, totalItemCount;
    int visibleThreshold = 1;
    ContentLoadingProgressBar contentLoadingProgressBar;
    private boolean isLoading = false;


contentLoadingProgressBar = view.findViewById(R.id.contentLoadingProgressBar);
 final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) postRecyclerView.getLayoutManager();
        postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) 
                super.onScrolled(recyclerView, dx, dy);

                int[] lastVisibleItemPositions = Objects.requireNonNull(linearLayoutManager).findLastVisibleItemPositions(null);
                int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
                int totalItemCount = linearLayoutManager.getItemCount();
                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) 
                    getData();
                    shimmerFrameLayout.startShimmer();
                    isLoading = true;
                
            
        );

public int getLastVisibleItem(int[] lastVisibleItemPositions) 
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) 
            if (i == 0) 
                maxSize = lastVisibleItemPositions[i];
             else if (lastVisibleItemPositions[i] > maxSize) 
                maxSize = lastVisibleItemPositions[i];
            
        
        return maxSize;
    

完整代码

public class Profile_Fragment extends Fragment implements PostAdapter.OnItemClickListener 
    public static List<Upload> mUploads;
    private final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
    PostAdapter postsAdapter;
    ShimmerFrameLayout shimmerFrameLayout;
    RecyclerView postRecyclerView;
    Button editProfileButton;
    CircleImageView profilePhoto;
    ContentLoadingProgressBar contentLoadingProgressBar;
    int visibleThreshold = 1;
    private FirebaseStorage mStorage;
    private ValueEventListener databaseEventListener;
    private boolean isLoading = false;

    @SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ImageView accountSettings = view.findViewById(R.id.account_Settings);
        RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile);
        profilePhoto = relativeLayout.findViewById(R.id.circleImageView);
        editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button);
        contentLoadingProgressBar = view.findViewById(R.id.contentLoadingProgressBar);
        editProfileButton.setOnClickListener(v -> 
            Fragment edit_profile = new Edit_Profile();
            assert getFragmentManager() != null;
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, edit_profile);
            transaction.addToBackStack(null);
            transaction.commit();
        );
        accountSettings.setOnClickListener(
                v -> 
                    BottomSheet bottomSheet = new BottomSheet();
                    bottomSheet.show(requireActivity().getSupportFragmentManager(), bottomSheet.getTag());
                
        );
        postRecyclerView = view.findViewById(R.id.postRecyclerViewProfile);
        shimmerFrameLayout = view.findViewById(R.id.shimmerEffect);
        postRecyclerView.setLayoutManager(
                new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        );
        final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) postRecyclerView.getLayoutManager();
        postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) 
                super.onScrolled(recyclerView, dx, dy);

                assert linearLayoutManager != null;
                int[] lastVisibleItemPositions = linearLayoutManager.findLastVisibleItemPositions(null);
                int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
                int totalItemCount = linearLayoutManager.getItemCount();
                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) 
                    isLoading = true;
                    getData();
                
            
        );
        mUploads = new ArrayList<>();
        postsAdapter = new PostAdapter(getContext(), mUploads);
        postRecyclerView.setAdapter(postsAdapter);
        postsAdapter.setOnItemClickListener(Profile_Fragment.this);
        return view;
    

    public int getLastVisibleItem(int[] lastVisibleItemPositions) 
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) 
            if (i == 0) 
                maxSize = lastVisibleItemPositions[i];
             else if (lastVisibleItemPositions[i] > maxSize) 
                maxSize = lastVisibleItemPositions[i];
            
        
        return maxSize;
    

    private void getData() 
        contentLoadingProgressBar.setVisibility(View.VISIBLE);
        mStorage = FirebaseStorage.getInstance();
        databaseEventListener = databaseReference.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) 
                if (snapshot.exists()) 
                    postRecyclerView.setVisibility(View.VISIBLE);
                    shimmerFrameLayout.stopShimmer();
                    shimmerFrameLayout.setVisibility(View.GONE);
                    contentLoadingProgressBar.setVisibility(View.GONE);
                    mUploads.clear();
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) 
                        Upload upload = dataSnapshot.getValue(Upload.class);
                        Objects.requireNonNull(upload).setmKey(dataSnapshot.getKey());
                        mUploads.add(upload);


                    

                

                //notify the adapter
                postsAdapter.notifyDataSetChanged();
            

            @Override
            public void onCancelled(@NonNull DatabaseError error) 
            
        );
    

    @Override
    public void onClick(View view) 

    

    @Override
    public void onItemClick(int position) 

    

    @Override
    public void onDeleteClick(int position) 
        Upload selectedItem = mUploads.get(position);
        String selectedKey = selectedItem.getmKey();
        StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getmImageUrl());
        imageRef.delete().addOnSuccessListener(aVoid -> 
            databaseReference.child(selectedKey).removeValue();
            Toast.makeText(getContext(), "Post Deleted", Toast.LENGTH_SHORT).show();
        )
                .addOnFailureListener(aVoid -> Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show());


    


    @Override
    public void onDestroyView() 
        super.onDestroyView();
        databaseReference.removeEventListener(databaseEventListener);
    


更新 1

添加了adapter.class

public class PostAdapter extends RecyclerView.Adapter<PostAdapter.PostViewHolder> 
    public static List<Upload> mUploads;
    public Context mcontext;
    private OnItemClickListener mListener;
//    ShimmerFrameLayout shimmerFrameLayout;


    public PostAdapter(Context context, List<Upload> uploads) 
        mUploads = uploads;
        mcontext = context;
    

    @NonNull
    @Override
    public PostViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) 
        View view;
        LayoutInflater.from(mcontext).inflate(R.layout.post_item_container_profile, parent, false);
        view = LayoutInflater.from(parent.getContext()).inflate(R.layout.post_item_container_profile, parent, false);
        return new PostViewHolder(view);

    

    @Override
    public void onBindViewHolder(@NonNull PostViewHolder holder, int position) 
        Upload uploadCurrent = mUploads.get(position);
        Shimmer shimmer = new Shimmer.ColorHighlightBuilder()
                .setBaseColor(Color.parseColor("#F3F3F3"))
                .setBaseAlpha(1)
                .setHighlightColor(Color.parseColor("#E7E7E7"))
                .setHighlightAlpha(1)
                .setDropoff(50)
                .build();
        ShimmerDrawable shimmerDrawable = new ShimmerDrawable();
        shimmerDrawable.setShimmer(shimmer);
        Glide.with(mcontext)
                .load(uploadCurrent.getmImageUrl())
                .diskCacheStrategy(DiskCacheStrategy.AUTOMATIC)
                .placeholder(shimmerDrawable)
                .centerCrop()
                .fitCenter()
                .into(holder.imageView);

    

    @Override
    public int getItemCount() 
        return mUploads.size();
    

    public void setOnItemClickListener(OnItemClickListener listener) 
        mListener = listener;

    

    public interface OnItemClickListener 
        void onClick(View view);

        void onItemClick(int position);

        void onDeleteClick(int position);
    

    public class PostViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener,
            View.OnCreateContextMenuListener, MenuItem.OnMenuItemClickListener 
        ShapeableImageView imageView;

        PostViewHolder(@NonNull View itemView) 
            super(itemView);
            imageView = itemView.findViewById(R.id.imagePost);

            itemView.setOnClickListener(this);
            itemView.setOnCreateContextMenuListener(this);
        

        @Override
        public void onClick(View v) 
            if (mListener != null) 
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) 
                    mListener.onItemClick(position);
                
            
        

        @Override
        public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo) 
            MenuItem delete = menu.add(Menu.NONE, 2, 2, "Delete");
            delete.setOnMenuItemClickListener(this);
        

        @Override
        public boolean onMenuItemClick(MenuItem item) 
            if (mListener != null) 
                int position = getAdapterPosition();
                if (position != RecyclerView.NO_POSITION) 
                    if (item.getItemId() == 2) 
                        mListener.onDeleteClick(position);
                        return true;
                    
                
            
            return false;
        
    

【问题讨论】:

您是否尝试过使用 Jetpack 中的Paging 不,我尝试过,因为我认为 jetpack 可能只能与 kotlin 一起使用 【参考方案1】:

试试这个。

public class Profile_Fragment extends Fragment implements PostAdapter.OnItemClickListener 
    public static List<Upload> mUploads = new ArrayList<>();
    private final DatabaseReference databaseReference = FirebaseDatabase.getInstance().getReference("uploads");
    PostAdapter  postsAdapter = new PostAdapter(getContext(), mUploads);;
    ShimmerFrameLayout shimmerFrameLayout;
    RecyclerView postRecyclerView;
    Button editProfileButton;
    CircleImageView profilePhoto;
    ContentLoadingProgressBar contentLoadingProgressBar;
    int visibleThreshold = 1;
    private FirebaseStorage mStorage;
    private ValueEventListener databaseEventListener;
    private boolean isLoading = false;

    @SuppressLint("SourceLockedOrientationActivity")
    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) 
        View view = inflater.inflate(R.layout.fragment_profile, container, false);
        requireActivity().setRequestedOrientation(ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);
        ImageView accountSettings = view.findViewById(R.id.account_Settings);
        RelativeLayout relativeLayout = view.findViewById(R.id.snipet_profile);
        profilePhoto = relativeLayout.findViewById(R.id.circleImageView);
        editProfileButton = relativeLayout.findViewById(R.id.edit_profile_button);
        contentLoadingProgressBar = view.findViewById(R.id.contentLoadingProgressBar);
        editProfileButton.setOnClickListener(v -> 
            Fragment edit_profile = new Edit_Profile();
            assert getFragmentManager() != null;
            FragmentTransaction transaction = getFragmentManager().beginTransaction();
            transaction.replace(R.id.fragment_container, edit_profile);
            transaction.addToBackStack(null);
            transaction.commit();
        );
        accountSettings.setOnClickListener(
                v -> 
                    BottomSheet bottomSheet = new BottomSheet();
                    bottomSheet.show(requireActivity().getSupportFragmentManager(), bottomSheet.getTag());
                
        );
        postRecyclerView = view.findViewById(R.id.postRecyclerViewProfile);
        shimmerFrameLayout = view.findViewById(R.id.shimmerEffect);
        postRecyclerView.setLayoutManager(
                new StaggeredGridLayoutManager(3, StaggeredGridLayoutManager.VERTICAL)
        );
        final StaggeredGridLayoutManager linearLayoutManager = (StaggeredGridLayoutManager) postRecyclerView.getLayoutManager();
          
        postRecyclerView.setAdapter(postsAdapter);

        postRecyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() 
            @Override
            public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy) 
                super.onScrolled(recyclerView, dx, dy);

                assert linearLayoutManager != null;
                int[] lastVisibleItemPositions = linearLayoutManager.findLastVisibleItemPositions(null);
                int lastVisibleItem = getLastVisibleItem(lastVisibleItemPositions);
                int totalItemCount = linearLayoutManager.getItemCount();
                if (!isLoading && totalItemCount <= (lastVisibleItem + visibleThreshold)) 
                    isLoading = true;
                    getData();
                
                postadapter.mUploads=mUploads

                  postsAdapter.notifyDataSetChanged();


            
        );
       
      
        postsAdapter.setOnItemClickListener(Profile_Fragment.this);
        return view;
    

    public int getLastVisibleItem(int[] lastVisibleItemPositions) 
        int maxSize = 0;
        for (int i = 0; i < lastVisibleItemPositions.length; i++) 
            if (i == 0) 
                maxSize = lastVisibleItemPositions[i];
             else if (lastVisibleItemPositions[i] > maxSize) 
                maxSize = lastVisibleItemPositions[i];
            
        
        return maxSize;
    

    private void getData() 
        contentLoadingProgressBar.setVisibility(View.VISIBLE);
        mStorage = FirebaseStorage.getInstance();
        databaseEventListener = databaseReference.addValueEventListener(new ValueEventListener() 
            @Override
            public void onDataChange(@NonNull DataSnapshot snapshot) 
                if (snapshot.exists()) 
                    postRecyclerView.setVisibility(View.VISIBLE);
                    shimmerFrameLayout.stopShimmer();
                    shimmerFrameLayout.setVisibility(View.GONE);
                    contentLoadingProgressBar.setVisibility(View.GONE);
                    mUploads.clear();
                    for (DataSnapshot dataSnapshot : snapshot.getChildren()) 
                        Upload upload = dataSnapshot.getValue(Upload.class);
                        Objects.requireNonNull(upload).setmKey(dataSnapshot.getKey());
                        mUploads.add(upload);


                    

                

                
            

            @Override
            public void onCancelled(@NonNull DatabaseError error) 
            
        );
    

    @Override
    public void onClick(View view) 

    

    @Override
    public void onItemClick(int position) 

    

    @Override
    public void onDeleteClick(int position) 
        Upload selectedItem = mUploads.get(position);
        String selectedKey = selectedItem.getmKey();
        StorageReference imageRef = mStorage.getReferenceFromUrl(selectedItem.getmImageUrl());
        imageRef.delete().addOnSuccessListener(aVoid -> 
            databaseReference.child(selectedKey).removeValue();
            Toast.makeText(getContext(), "Post Deleted", Toast.LENGTH_SHORT).show();
        )
                .addOnFailureListener(aVoid -> Toast.makeText(getContext(), "Failed", Toast.LENGTH_SHORT).show());


    


    @Override
    public void onDestroyView() 
        super.onDestroyView();
        databaseReference.removeEventListener(databaseEventListener);
    


如果不工作请告诉我.....

【讨论】:

你能发布你的adatper类代码文件吗,比如adapter.java 好的,我已经添加了适配器类,请立即查看 我是否应该在您添加更改后更新我的问题,以便您查看我所做的更改

以上是关于分页不适用于交错网格布局android的主要内容,如果未能解决你的问题,请参考以下文章

交错网格布局行为问题

在两个方向上工作的交错网格布局管理器

Android零基础入门第32节:新推出的GridLayout网格布局

GridLayout(网格布局)

学会使用Android Studio网格布局制作计算器界面

Grid布局和Flex布局.md