代码之家  ›  专栏  ›  技术社区  ›  SudoPlz

如何防止RecyclerView单元格的子单元格在用户滚动时移动

  •  8
  • SudoPlz  · 技术社区  · 7 年前

    我有很长宽度的单元格 水平的 RecyclerView ,则, 我希望它们有一个标题,在用户水平滚动时保持不变。

    - Recycler View (A)
    -   -   Cell (parent) (B)
    -   -   -   Header (C) <-- We want that to be still
    -   -   -   Content (D)
    

    以下是它的视觉效果:

    因此,我正在寻找一种方法:

    1) 停止 标题 (C) 当用户在 回收视图 (A)

    2) 像正常一样滚动单元格(B),但是 将其子级(C)的位置更改为相反方向 ,以便制作页眉 显示静止 即使它正在移动(与父对象(B)的方向相反)。

    以下是我试图构建的内容:

    有什么想法吗?

    p、 学生1:我注意到很多答案,建议使用 ItemDecoration ,但所有可能的答案都有代码 VERTICAL 实现,这与 HORIZONTAL 实施。

    p、 我正在以编程方式创建所有视图内容,因此我不会使用布局文件。(这是因为内容将是react本机视图,我无法创建带有布局文件的视图)。

    p、 学生3:我也注意到 项目装饰 是一种古老的策略,最近的第三方库扩展了 LayoutManager

    请说清楚,谢谢。

    4 回复  |  直到 7 年前
        1
  •  4
  •   Cheticamp    7 年前

    虽然可以将标题视图保留在 RecyclerView 我建议采用另一种方法。

    标题可以继续在 回收视图 ,但显示屏将显示在 回收视图 具体如下:

    - Title (C) <-- We want that to be still
    - Recycler View (A)
    -   -   Cell (parent) (B)
    -   -   -   Content
    

    A. RecyclerView.OnScrollListener 将侦听新项目的外观并相应更改标题。这样,当新项目出现时,标题 TextView 将显示新标题。下面演示了这一点。

    enter image description here

    (这是一个用于演示的简单实现。一个完整的应用程序将显示犬种图像和某种有意义的描述。)

    以下是实现此效果的代码:

    主要活动。Java语言

    public class MainActivity extends AppCompatActivity {
        private LinearLayoutManager mLayoutManager;
        private RecyclerViewAdapter mAdapter;
        private TextView mBreedNameTitle;
        private int mLastBreedTitlePosition = RecyclerView.NO_POSITION;
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            List<String> breedList = createBreedList();
    
            // This is where the breed title is displayed.
            mBreedNameTitle = findViewById(R.id.breedNameTitle);
    
            // Set up the RecyclerView.
            mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
            RecyclerView recyclerView = findViewById(R.id.recyclerView);
            mAdapter = new RecyclerViewAdapter(breedList);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setAdapter(mAdapter);
    
            // Add the OnScrollListener so we know when to change the breed title.
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
    
                    int lastVisible = mLayoutManager.findLastVisibleItemPosition();
                    if (lastVisible == RecyclerView.NO_POSITION) {
                        return;
                    }
                    if (lastVisible != mLastBreedTitlePosition) {
                        mBreedNameTitle.setText(mAdapter.getItems().get(lastVisible));
                        mLastBreedTitlePosition = lastVisible;
                    }
                }
            });
        }
    
        private List<String> createBreedList() {
            List<String> breedList = new ArrayList<>();
            breedList.add("Affenpinscher");
            breedList.add("Afghan Hound");
            breedList.add("Airedale Terrier");
            breedList.add("Akita");
            breedList.add("Alaskan Malamute");
            breedList.add("American Cocker Spaniel");
            breedList.add("American Eskimo Dog (Miniature)");
            breedList.add("American Eskimo Dog (Standard)");
            breedList.add("American Eskimo Dog (Toy)");
            breedList.add("American Foxhound");
            breedList.add("American Staffordshire Terrier");
            breedList.add("American Eskimo Dog (Standard)");
            return breedList;
        }
    
        @SuppressWarnings("unused")
        private final static String TAG = "MainActivity";
    }
    
    class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private final List<String> mItems;
    
        RecyclerViewAdapter(List<String> items) {
            mItems = items;
        }
    
        @Override
        @NonNull
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
    
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
            return new RecyclerViewAdapter.ItemViewHolder(view);
        }
    
    
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            RecyclerViewAdapter.ItemViewHolder vh = (RecyclerViewAdapter.ItemViewHolder) holder;
    
            vh.mBreedImage.setImageDrawable(holder.itemView.getResources().getDrawable(R.drawable.no_image));
            vh.mBreedName = mItems.get(position);
        }
    
        @Override
        public int getItemCount() {
            return mItems.size();
        }
    
        public List<String> getItems() {
            return mItems;
        }
    
        static class ItemViewHolder extends RecyclerView.ViewHolder {
            private ImageView mBreedImage;
            private String mBreedName;
    
            ItemViewHolder(View itemView) {
                super(itemView);
                mBreedImage = itemView.findViewById(R.id.breedImage);
            }
        }
    }
    

    activity\u main。xml

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:orientation="vertical">
    
        <TextView
            android:id="@+id/breedNameTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:fontFamily="sans-serif"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            tools:text="Breed name" />
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" />
    </LinearLayout>
    

    item\u布局。xml

    <android.support.constraint.ConstraintLayout 
        android:id="@+id/cont_item_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">
    
        <ImageView
            android:id="@+id/breedImage"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:contentDescription="Dog breed image"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toTopOf="parent"
            app:layout_constraintVertical_bias="1.0"
            tools:ignore="HardcodedText" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginEnd="16dp"
            android:layout_marginStart="16dp"
            android:text="@string/large_text"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/breedImage"
            app:layout_constraintTop_toTopOf="parent" />
    
    </android.support.constraint.ConstraintLayout>
    

    更新时间: 下面是另一种设置 文本框 使收割台粘滞。的负x偏移 文本框 用作页眉的填充,使其在 文本框 然后粘在屏幕的左侧。

    结果如下:

    enter image description here

    主要活动。Java语言

    public class MainActivity extends AppCompatActivity {
        private LinearLayoutManager mLayoutManager;
    
        protected void onCreate(Bundle savedInstanceState) {
            super.onCreate(savedInstanceState);
            setContentView(R.layout.activity_main);
    
            List<String> breedList = createBreedList();
    
            // Set up the RecyclerView.
            mLayoutManager = new LinearLayoutManager(this, LinearLayoutManager.HORIZONTAL, false);
            RecyclerView recyclerView = findViewById(R.id.recyclerView);
            RecyclerViewAdapter adapter = new RecyclerViewAdapter(breedList);
            recyclerView.setLayoutManager(mLayoutManager);
            recyclerView.setAdapter(adapter);
    
            recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener() {
                @Override
                public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                    super.onScrolled(recyclerView, dx, dy);
    
                    // Pad the left of the breed name so it stays aligned with the left side of the display.
                    int firstVisible = mLayoutManager.findFirstVisibleItemPosition();
                    View firstView = mLayoutManager.findViewByPosition(firstVisible);
                    firstView.findViewById(R.id.itemBreedName).setPadding((int) -firstView.getX(), 0, 0, 0);
    
                    // Make sure the other breed name has zero padding because we may have changed it.
                    int lastVisible = mLayoutManager.findLastVisibleItemPosition();
                    View lastView = mLayoutManager.findViewByPosition(lastVisible);
                    lastView.findViewById(R.id.itemBreedName).setPadding(0, 0, 0, 0);
                }
            });
        }
    
        private List<String> createBreedList() {
            List<String> breedList = new ArrayList<>();
            breedList.add("Affenpinscher");
            breedList.add("Afghan Hound");
            breedList.add("Airedale Terrier");
            breedList.add("Akita");
            breedList.add("Alaskan Malamute");
            breedList.add("American Cocker Spaniel");
            breedList.add("American Eskimo Dog (Miniature)");
            breedList.add("American Eskimo Dog (Standard)");
            breedList.add("American Eskimo Dog (Toy)");
            breedList.add("American Foxhound");
            breedList.add("American Staffordshire Terrier");
            breedList.add("American Eskimo Dog (Standard)");
            return breedList;
        }
    
        @SuppressWarnings("unused")
        private final static String TAG = "MainActivity";
    
    }
    
    class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
        private final List<String> mItems;
    
        RecyclerViewAdapter(List<String> items) {
            mItems = items;
        }
    
        @Override
        @NonNull
        public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
            View view;
    
            view = LayoutInflater.from(parent.getContext()).inflate(R.layout.item_layout, parent, false);
            return new RecyclerViewAdapter.ItemViewHolder(view);
        }
    
    
        @Override
        public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {
            RecyclerViewAdapter.ItemViewHolder vh = (RecyclerViewAdapter.ItemViewHolder) holder;
    
            vh.mBreedImage.setImageDrawable(holder.itemView.getResources().getDrawable(R.drawable.no_image));
            vh.mBreedName.setPadding(0, 0, 0, 0);
            vh.mBreedName.setText(mItems.get(position));
        }
    
        @Override
        public int getItemCount() {
            return mItems.size();
        }
    
        static class ItemViewHolder extends RecyclerView.ViewHolder {
            private ImageView mBreedImage;
            private TextView mBreedName;
    
            ItemViewHolder(View itemView) {
                super(itemView);
                mBreedImage = itemView.findViewById(R.id.breedImage);
                mBreedName = itemView.findViewById(R.id.itemBreedName);
            }
        }
    }
    

    activity\u main。xml

    <LinearLayout 
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_margin="@dimen/activity_horizontal_margin"
        android:orientation="vertical">
    
        <android.support.v7.widget.RecyclerView
            android:id="@+id/recyclerView"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="horizontal" />
    </LinearLayout>
    

    item\u布局。xml

    <android.support.constraint.ConstraintLayout 
        android:id="@+id/cont_item_root"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:background="@android:color/white">
    
        <TextView
            android:id="@+id/itemBreedName"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginEnd="8dp"
            android:layout_marginStart="8dp"
            android:ellipsize="none"
            android:fontFamily="sans-serif"
            android:singleLine="true"
            android:textColor="@android:color/black"
            android:textSize="16sp"
            tools:text="Breed name" />
    
        <ImageView
            android:id="@+id/breedImage"
            android:layout_width="64dp"
            android:layout_height="64dp"
            android:layout_marginBottom="8dp"
            android:layout_marginEnd="8dp"
            android:contentDescription="Dog breed image"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintStart_toStartOf="parent"
            app:layout_constraintTop_toBottomOf="@+id/itemBreedName"
            app:layout_constraintVertical_bias="1.0"
            tools:ignore="HardcodedText" />
    
        <TextView
            android:id="@+id/textView"
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_marginEnd="16dp"
            android:layout_marginStart="16dp"
            android:text="@string/large_text"
            app:layout_constraintBottom_toBottomOf="parent"
            app:layout_constraintEnd_toEndOf="parent"
            app:layout_constraintStart_toEndOf="@+id/breedImage"
            app:layout_constraintTop_toBottomOf="@+id/itemBreedName" />
    
    </android.support.constraint.ConstraintLayout>
    
        2
  •  1
  •   ColdFire    7 年前

    希望此库帮助: TableView

    <com.evrencoskun.tableview.TableView
        android:id="@+id/content_container"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
    
        app:column_header_height="@dimen/column_header_height"
        app:row_header_width="@dimen/row_header_width"
        app:selected_color="@color/selected_background_color"
        app:shadow_color="@color/shadow_background_color"
        app:unselected_color="@color/unselected_background_color" />
    
        3
  •  0
  •   Tuby    7 年前

    我用这个答案作为解决方案 stackoverflow.com/a/44327350/4643073 效果很好!

    如果您想要水平粘性标题,只需更改所有与“垂直性”相关的内容,更改 getY() getX() ,则, getTop() getRight() ,则, getHeight() getWidth()

    你为什么认为 ItemDecoration 这是旧策略吗?它没有被弃用,它不会弄乱适配器以扩展某些特定的类,它工作得很好。

        4
  •  0
  •   SudoPlz    6 年前

    我最终做了以下事情(感谢切蒂坎普给我的灵感):

    - Helper Header (C) <-- We now have an extra title view
    - Recycler View (A)
    -   -   Cell (parent) (B)
    -   -   -   Header (C) <-- Plus the typical titles within our cells
    -   -   -   Content
    

    如您所见:

    • 我们现在有了一个位于RecyclerView之外的helper头视图
    • 位于我们的RecyclerView中的标题视图一直在移动,但在它们的正上方我们放置了helper视图

    下面是一些实际的代码来了解发生了什么:

    公共类CalendarView扩展了LinearLayout{ 受保护的LinearLayoutManager mLayoutManager; 受保护的HeaderView helperHeaderView; 受保护的RecyclerView RecyclerView;

    public CalendarView(final ReactContext context) {
        super(context);
    
    
        setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
        setOrientation(LinearLayout.VERTICAL);
    
        helperHeaderView = new HeaderView(context);
        addView(helperHeaderView);
    
    
    
    
        final DailyViewAdapter adapter = new DailyViewAdapter(context) {
            @Override
            public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
                super.onBindViewHolder(holder, position);
    
                // if our header is not assinged any position yet (we haven't given it any data yet)
                if (helperHeaderView.getLastPosition() == null) {
                    updateHeaderData(helperHeaderView, globals.getInitialPosition()); // hydrate it
                }
            }
        };
    
        recyclerView = new SPRecyclerView(context) {
            @Override
            public void onScrolled(RecyclerView recyclerView, int dx, int dy) {
                super.onScrolled(recyclerView, dx, dy);
    
                if (mLayoutManager == null) {
                    mLayoutManager = (LinearLayoutManager) getLayoutManager();
                }
    
                // the width of any header
                int headerWidth = helperHeaderView.getWidth();
    
                // get the position of the first visible header in the recyclerview
                int firstVisiblePos = mLayoutManager.findFirstVisibleItemPosition();
    
                // get a ref of the Cell that contains that header
                DayView firstView = (DayView) mLayoutManager.findViewByPosition(firstVisiblePos);
    
                // get the X coordinate of the first visible header
                float firstViewX = firstView.getX();
    
    
    
                // get the position of the last visible header in the recyclerview
                int lastVisiblePos = mLayoutManager.findLastVisibleItemPosition();
    
                // get a ref of the Cell that contains that header
                DayView lastView = (DayView) mLayoutManager.findViewByPosition(lastVisiblePos);
    
                // get the X coordinate of the last visible header
                float lastViewX = lastView.getX();
    
    
                // if the first visible position is not the one our header is set to
                if (helperHeaderView.getLastPosition() != firstVisiblePos) {
                    // update the header data
                    adapter.updateHeaderData(helperHeaderView, firstVisiblePos);
                }
    
                // if the first visible is not also the last visible (happens when there's only one Cell on screen)
                if (firstVisiblePos == lastVisiblePos) {
                    // reset the X coordinates
                    helperHeaderView.setX(0);
                } else { // else if there are more than one cells on screen
                    // set the X of the helper header, to whatever the last visible header X was, minus the width of the header
                    helperHeaderView.setX(lastViewX - headerWidth);
                }
    
            }
        };
    
    
        // ...
    
    • 现在要做的就是将父布局转换为 RelativeLayout 为了使实际视图重叠(助手标题视图位于回收器视图的正上方)。

    • 此外,您可能希望在需要时尝试将辅助视图alpha设置为零,以确保其外观良好

    我希望这对将来的人有所帮助。