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

Vô hiệu hóa cuộn (scrolling) GridView trên Android

Giới thiệu

Ví dụ này minh họa cách ngăn chặn cuộn dọc trên GridView bằng cách gán OnTouchListener trả về true cho event ACTION_MOVE (chặn lan truyền touch), nhưng vẫn cho phép click item.

Bước 1: Tạo dự án mới

Tạo project Android Studio: File → New Project.

Bước 2: Layout (res/layout/activity_main.xml)

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="https://schemas.android.com/apk/res/android"
    xmlns:tools="https://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:padding="8dp"
    tools:context=".MainActivity">

    <GridView
        android:id="@+id/gridLayout"
        android:layout_width="match_parent"
        android:layout_height="match_parent" />

</RelativeLayout>

Bước 3: MainActivity - GridView với BaseAdapter và chặn scroll

Set OnTouchListener: nếu action là ACTION_MOVE thì return true (consume event, không scroll), ngược lại return false (cho click-through). Adapter load 10 ảnh drawable.

import androidx.appcompat.app.AppCompatActivity;
import android.annotation.SuppressLint;
import android.content.Context;
import android.os.Bundle;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.Toast;

public class MainActivity extends AppCompatActivity {
    GridView gridView;
    Integer[] imageIDs = {R.drawable.one, R.drawable.two, R.drawable.three, R.drawable.four, R.drawable.five,
                          R.drawable.six, R.drawable.seven, R.drawable.eight, R.drawable.nine, R.drawable.ten};

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

        gridView = findViewById(R.id.gridLayout);
        gridView.setAdapter(new ImageAdapterGridView(this));

        gridView.setOnTouchListener((v, event) -> {
            if (event.getAction() == MotionEvent.ACTION_MOVE) {
                Toast.makeText(MainActivity.this, "Cuộn đã bị vô hiệu hóa", Toast.LENGTH_SHORT).show();
                return true; // Chặn scroll
            }
            return false; // Cho phép click (ACTION_DOWN/UP)
        });
    }

    public class ImageAdapterGridView extends BaseAdapter {
        private Context context;
        ImageAdapterGridView(Context c) { context = c; }
        public int getCount() { return imageIDs.length; }
        public Object getItem(int position) { return null; }
        public long getItemId(int position) { return 0; }
        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;
            if (convertView == null) {
                imageView = new ImageView(context);
                imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.MATCH_PARENT));
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(20, 20, 20, 20);
            } else {
                imageView = (ImageView) convertView;
            }
            imageView.setImageResource(imageIDs[position]);
            return imageView;
        }
    }
}

Bước 4: Manifest

<?xml version="1.0" encoding="utf-8"?>
<manifest xmlns:android="https://schemas.android.com/apk/res/android" package="app.com.sample">
    <application
        android:allowBackup="true"
        android:icon="@mipmap/ic_launcher"
        android:label="@string/app_name"
        android:roundIcon="@mipmap/ic_launcher_round"
        android:supportsRtl="true"
        android:theme="@style/AppTheme">
        <activity android:name=".MainActivity">
            <intent-filter>
                <action android:name="android.intent.action.MAIN" />
                <category android:name="android.intent.category.LAUNCHER" />
            </intent-filter>
        </activity>
    </application>
</manifest>

Chạy ứng dụng

Chạy app, GridView hiển thị 10 ảnh. Kéo dọc sẽ hiện Toast "Cuộn đã bị vô hiệu hóa" và không cuộn. Click vào ảnh vẫn hoạt động bình thường (nếu set OnItemClickListener).

Lưu ý & Cách tốt hơn

  • Cách này chặn tất cả ACTION_MOVE, có thể gây lag nếu GridView lớn.
  • Khuyến nghị dùng RecyclerView với GridLayoutManager và override canScrollVertically() return false, hoặc set setNestedScrollingEnabled(false).
  • Nếu GridView nằm trong ScrollView (nested scrolling), dùng NestedScrollView + RecyclerView với setNestedScrollingEnabled(false).
  • Để GridView không scroll nhưng vẫn fill parent, set height = wrap_content trong ScrollView cha.