Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Android

Cuộn lên đầu RecyclerView với LinearLayoutManager Android

RecyclerView scrollToPosition / smoothScrollToPosition

Để cuộn RecyclerView về vị trí nhất định (ví dụ top - vị trí 0), dùng recyclerView.smoothScrollToPosition(0) cho hiệu ứng mượt hoặc scrollToPosition(0) cho nhảy ngay lập tức.

Xây dựng App Danh sách Sinh viên

1. build.gradle (dependencies)

dependencies {
    implementation 'androidx.appcompat:appcompat:1.6.1'
    implementation 'com.google.android.material:material:1.9.0'
    implementation 'androidx.recyclerview:recyclerview:1.3.0'
    implementation 'androidx.cardview:cardview:1.0.0'
    // ... các dependency khác
}

2. Layout activity_main.xml (CoordinatorLayout + FAB)

<?xml version="1.0" encoding="utf-8"?>
<androidx.coordinatorlayout.widget.CoordinatorLayout
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:app="https://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <androidx.recyclerview.widget.RecyclerView
        android:id="@+id/recycler_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scrollbars="vertical" />

    <com.google.android.material.floatingactionbutton.FloatingActionButton
        android:id="@+id/fab_top"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_gravity="bottom|end"
        android:layout_margin="16dp"
        android:src="@android:drawable/arrow_up_float"
        app:backgroundTint="#FFD600"
        app:tint="@android:color/black" />

</androidx.coordinatorlayout.widget.CoordinatorLayout>

3. Item layout: res/layout/student_list_row.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.cardview.widget.CardView
    xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:card_view="https://schemas.android.com/apk/res-auto"
    android:id="@+id/card_view"
    android:layout_width="match_parent"
    android:layout_height="200dp"
    android:layout_margin="10dp"
    card_view:cardCornerRadius="8dp"
    card_view:cardElevation="4dp">

    <LinearLayout
        android:id="@+id/parent"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical"
        android:gravity="center">

        <TextView android:id="@+id/name"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:textColor="#FFF" />

        <TextView android:id="@+id/age"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:textSize="24sp"
            android:textColor="#FFF" />

    </LinearLayout>
</androidx.cardview.widget.CardView>

4. Model: Student.java

public class Student {
    public String name;
    public int age;
    public Student(String name, int age) {
        this.name = name; this.age = age;
    }
}

5. Adapter: StudentAdapter.java

public class StudentAdapter extends RecyclerView.Adapter<StudentAdapter.VH> {
    private List<Student> list;
    public StudentAdapter(List<Student> list) { this.list = list; }

    @NonNull @Override
    public VH onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {
        View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.student_list_row, parent, false);
        return new VH(v);
    }

    @Override
    public void onBindViewHolder(@NonNull VH holder, int position) {
        Student s = list.get(position);
        holder.name.setText(s.name);
        holder.age.setText(s.age + " tuổi");
        // Màu ngẫu nhiên cho đẹp
        int color = Color.argb(255, new Random().nextInt(256), new Random().nextInt(256), new Random().nextInt(256));
        holder.parent.setBackgroundColor(color);
    }

    @Override public int getItemCount() { return list.size(); }

    static class VH extends RecyclerView.ViewHolder {
        TextView name, age; LinearLayout parent;
        VH(View v) { super(v); name=v.findViewById(R.id.name); age=v.findViewById(R.id.age); parent=v.findViewById(R.id.parent); }
    }
}

6. MainActivity.java - Logic cuộn lên đầu

public class MainActivity extends AppCompatActivity {
    RecyclerView recyclerView;
    StudentAdapter adapter;
    List<Student> data = new ArrayList<>();

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerView = findViewById(R.id.recycler_view);
        FloatingActionButton fabTop = findViewById(R.id.fab_top);

        recyclerView.setLayoutManager(new LinearLayoutManager(this));
        adapter = new StudentAdapter(data);
        recyclerView.setAdapter(adapter);

        prepareData();

        fabTop.setOnClickListener(v -> {
            // Cuộn mượt về vị trí 0 (đầu danh sách)
            recyclerView.smoothScrollToPosition(0);
        });
    }

    void prepareData() {
        data.add(new Student("Sai", 25));
        data.add(new Student("Sai Raj", 25));
        data.add(new Student("Raghu", 20));
        data.add(new Student("Raj", 28));
        data.add(new Student("Amar", 15));
        data.add(new Student("Bapu", 19));
        data.add(new Student("Chandra", 52));
        data.add(new Student("Deraj", 30));
        data.add(new Student("Eshanth", 28));
        // Sắp xếp tên
        Collections.sort(data, (o1, o2) -> o1.name.compareTo(o2.name));
        adapter.notifyDataSetChanged();
    }
}

Kết quả

Nhấn FAB mũi tên lên → RecyclerView cuộn mượt về item đầu tiên.