随手记->Glide初始化

本文介绍了解决Glide在Android应用中初次加载图片时导致UI卡顿的问题。通过在后台线程初始化Glide,避免了主线程阻塞,提高了用户体验。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

在项目中使用Glide加载图片,进入主页有一个列表需要显示,当下滑需要显示图片的时候,总是会卡一下,之后又不会卡了。

使用traceview定位发现首次使用Glide的时候,VM需要加载Glide里面相关的类,但是Glide的类太多了,加载起来竟然耗时超过了1s,无法接受。。。


解决办法:使用线程初始化Glide,代码如下,

    public static void initGlide(Context cxt) {
        final Context context = cxt.getApplicationContext();
        new Thread(new Runnable() {
            @Override
            public void run() {
                //下面用到的url最好是不存在的,目的只是为了初始化Glide
                Glide.with(context).load("/sdcard/xxx.jpg").into(1, 1);
                Glide.with(context).load("http://sdcard/xxx.jpg").into(1, 1);
            }
        }, "init_glide").start();

    }

在application的onCreate方法中使用上诉代码初始化后,则不会出现因首次初始化Glide而出现的卡顿。

延伸阅读->java加载类机制详解

<?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/gradient_background"> <!-- 标题栏 --> <RelativeLayout android:id="@+id/toolbar" android:layout_width="match_parent" android:layout_height="?android:attr/actionBarSize" android:background="#44bd32"> <Button android:id="@+id/fanHui" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_centerVertical="true" android:layout_marginStart="8dp" android:layout_marginEnd="8dp" android:background="@android:color/transparent" android:foreground="?android:attr/selectableItemBackground" android:text="返回" android:textColor="@android:color/white" android:textSize="16sp" /> </RelativeLayout> <!-- 底部按钮 --> <LinearLayout android:id="@+id/footer_buttons" android:layout_width="match_parent" android:layout_height="1dp" android:layout_alignParentBottom="true" android:background="@android:color/white" android:orientation="horizontal"> <!-- <Button--> <!-- android:id="@+id/device_location"--> <!-- android:layout_width="match_parent"--> <!-- android:layout_height="match_parent"--> <!-- android:gravity="center"--> <!-- android:text="设备定位"--> <!-- android:textSize="19sp"--> <!-- android:background="#44bd32"--> <!-- android:textColor="@android:color/white" />--> </LinearLayout> <RelativeLayout android:id="@+id/video_container" android:layout_width="match_parent" android:layout_height="380dp" android:layout_above="@id/footer_buttons" android:layout_below="@id/toolbar" android:layout_marginBottom="298dp" android:background="@android:color/black" android:padding="0dp"> <!-- 视频播放器 --> <VideoView android:id="@+id/video_player" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_centerInParent="true" /> <!-- 播放控制条 --> <LinearLayout android:layout_width="match_parent" android:layout_height="wrap_content" android:layout_alignParentBottom="true" android:background="#99000000" android:orientation="horizontal" android:padding="8dp"> <ImageButton android:id="@+id/btn_play_pause" android:layout_width="40dp" android:layout_height="40dp" android:background="?attr/selectableItemBackgroundBorderless" android:src="@drawable/ic_play_sel" /> <SeekBar android:id="@+id/video_seekbar" android:layout_width="0dp" android:layout_height="wrap_content" android:layout_weight="1" android:layout_gravity="center_vertical" /> <TextView android:id="@+id/tv_time" android:layout_width="wrap_content" android:layout_height="wrap_content" android:layout_gravity="center_vertical" android:text="00:00/00:00" android:textColor="@android:color/white" android:textSize="14sp" /> </LinearLayout> </RelativeLayout> <GridLayout android:id="@+id/thumbnail_grid" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/footer_buttons" android:layout_below="@id/video_container" android:layout_marginBottom="300dp" android:background="@android:color/white" android:columnCount="4" android:padding="8dp" android:rowCount="2"> <!-- 动态添加的缩略图将放在这里 --> <!-- 示例缩略图 (可选) --> <ImageView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="4dp" android:adjustViewBounds="true" android:contentDescription="萤石缩略图" android:src="@drawable/default_thumbnail"/> <ImageView android:layout_width="0dp" android:layout_height="wrap_content" android:layout_margin="4dp" android:adjustViewBounds="true" android:contentDescription="萤石缩略图" android:src="@drawable/default_thumbnail" /> <!-- 更多缩略图... --> </GridLayout> </RelativeLayout> 把萤石缩略图放在android:id="@+id/thumbnail_grid"模块中。
最新发布
06-27
<think>我们将在一个GridLayout中动态添加多个ImageView作为萤石视频的缩略图。步骤:1.在布局文件中,我们已经有一个GridLayout,其id为`thumbnail_grid`,并设置为4列。2.在Java代码中,我们将获取这个GridLayout,然后根据数据(比如从网络获取的缩略图URL列表)动态添加ImageView。3.每个ImageView将加载一个缩略图,并设置点击事件(例如点击后播放对应的视频)。注意:由于GridLayout是4列,所以我们可以按行添加。每个子视图需要指定在GridLayout中的位置。以下是如何在Java代码中动态添加缩略图的步骤:假设我们有一个缩略图URL列表:`List<String>thumbnailUrls`在Activity中:-获取GridLayout:`GridLayoutthumbnailGrid=findViewById(R.id.thumbnail_grid);`-清除所有已有视图(除了示例视图,但通常我们会全部清除然后动态添加):`thumbnailGrid.removeAllViews();`-遍历URL列表,为每个URL创建一个ImageView,并添加到GridLayout中。由于GridLayout已经设置了columnCount=4,所以每行可以放4个。我们只需要按顺序添加,GridLayout会自动排列。但是,我们需要为每个ImageView设置布局参数,以控制其大小和位置。示例代码:我们将设置每个ImageView的宽度为屏幕宽度的1/4(减去内边距和间距),高度根据宽高比调整(例如16:9)。步骤:1.计算每个缩略图的宽度:屏幕宽度减去GridLayout的内边距和列之间的间距,然后除以4。2.根据宽高比计算高度(例如16:9,则高度=宽度*9/16)。3.使用Glide加载图片到ImageView。同时,为每个ImageView添加点击事件,点击时播放对应的视频。注意:由于萤石视频可能需要不同的处理,这里我们假设每个缩略图对应一个视频片段,点击后播放该片段。下面是在Activity中动态添加缩略图的代码示例:</think>### 解决方案:在 GridLayout 中动态添加萤石缩略图 以下是完整的解决方案,包含布局修改和 Java 代码实现,用于在 `thumbnail_grid` GridLayout 中动态添加萤石视频缩略图: #### 1. 修改布局文件 (XML) 优化 `thumbnail_grid` 布局,添加更多灵活性和动态加载能力: ```xml <?xml version="1.0" encoding="utf-8"?> <RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" xmlns:app="http://schemas.android.com/apk/res-auto" android:layout_width="match_parent" android:layout_height="match_parent" android:background="@drawable/gradient_background"> <!-- ... 其他布局保持不变 ... --> <!-- 缩略图网格布局 --> <GridLayout android:id="@+id/thumbnail_grid" android:layout_width="match_parent" android:layout_height="match_parent" android:layout_above="@id/footer_buttons" android:layout_below="@id/video_container" android:layout_marginBottom="300dp" android:background="@android:color/white" android:columnCount="4" <!-- 4列网格 --> android:rowCount="2" <!-- 2行网格 --> android:padding="8dp" android:orientation="horizontal"> <!-- 所有缩略图将通过代码动态添加 --> </GridLayout> </RelativeLayout> ``` #### 2. Java 代码实现 在 Activity 中添加动态加载缩略图的逻辑: ```java public class VideoPlayerActivity extends AppCompatActivity { private GridLayout thumbnailGrid; private List<String> thumbnailUrls = new ArrayList<>(); // 存储缩略图URL private List<String> videoUrls = new ArrayList<>(); // 存储对应的视频URL @Override protected void onCreate(Bundle savedInstanceState) { super.onCreate(savedInstanceState); setContentView(R.layout.your_layout); // 初始化缩略图网格 thumbnailGrid = findViewById(R.id.thumbnail_grid); // 加载缩略图数据 loadThumbnails(); } // 加载缩略图数据(示例数据) private void loadThumbnails() { // 模拟数据 - 实际应用中应从API或本地获取 thumbnailUrls.add("https://example.com/thumbnail1.jpg"); thumbnailUrls.add("https://example.com/thumbnail2.jpg"); thumbnailUrls.add("https://example.com/thumbnail3.jpg"); thumbnailUrls.add("https://example.com/thumbnail4.jpg"); thumbnailUrls.add("https://example.com/thumbnail5.jpg"); thumbnailUrls.add("https://example.com/thumbnail6.jpg"); thumbnailUrls.add("https://example.com/thumbnail7.jpg"); thumbnailUrls.add("https://example.com/thumbnail8.jpg"); // 对应的视频URL videoUrls.add("https://example.com/video1.mp4"); videoUrls.add("https://example.com/video2.mp4"); // ... 添加其他视频URL // 动态添加缩略图 addThumbnailsToGrid(); } // 动态添加缩略图到网格 private void addThumbnailsToGrid() { thumbnailGrid.removeAllViews(); // 清除现有视图 // 计算缩略图尺寸 int screenWidth = getResources().getDisplayMetrics().widthPixels; int padding = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()); int thumbnailSize = (screenWidth - padding) / thumbnailGrid.getColumnCount(); // 添加缩略图 for (int i = 0; i < thumbnailUrls.size(); i++) { // 创建缩略图视图 ImageView thumbnail = new ImageView(this); // 设置布局参数 GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.width = thumbnailSize; params.height = thumbnailSize; params.setMargins(4, 4, 4, 4); params.columnSpec = GridLayout.spec(i % thumbnailGrid.getColumnCount()); params.rowSpec = GridLayout.spec(i / thumbnailGrid.getColumnCount()); thumbnail.setLayoutParams(params); // 加载图片 Glide.with(this) .load(thumbnailUrls.get(i)) .placeholder(R.drawable.default_thumbnail) // 默认图 .error(R.drawable.error_thumbnail) // 错误图 .override(thumbnailSize, thumbnailSize) // 指定尺寸 .centerCrop() .into(thumbnail); // 设置点击事件 final int position = i; thumbnail.setOnClickListener(v -> { // 播放对应视频 playVideo(videoUrls.get(position)); }); // 添加到网格 thumbnailGrid.addView(thumbnail); } } // 播放视频方法 private void playVideo(String videoUrl) { VideoView videoPlayer = findViewById(R.id.video_player); MediaController mediaController = new MediaController(this); mediaController.setAnchorView(videoPlayer); videoPlayer.setMediaController(mediaController); videoPlayer.setVideoURI(Uri.parse(videoUrl)); videoPlayer.start(); } } ``` ### 关键实现说明 #### 1. 动态布局计算 ```java // 计算缩略图尺寸 int screenWidth = getResources().getDisplayMetrics().widthPixels; int padding = (int) TypedValue.applyDimension( TypedValue.COMPLEX_UNIT_DIP, 16, getResources().getDisplayMetrics()); int thumbnailSize = (screenWidth - padding) / thumbnailGrid.getColumnCount(); ``` - 自动计算每个缩略图的大小 - 根据屏幕宽度和列数动态调整 - 考虑内边距确保布局美观 #### 2. 网格位置计算 ```java // 确定缩略图在网格中的位置 GridLayout.LayoutParams params = new GridLayout.LayoutParams(); params.columnSpec = GridLayout.spec(i % thumbnailGrid.getColumnCount()); params.rowSpec = GridLayout.spec(i / thumbnailGrid.getColumnCount()); ``` - 使用模运算 `%` 计算列位置 - 使用整数除法 `/` 计算行位置 - 自动适配网格布局 #### 3. 图片加载优化 ```java // 使用Glide高效加载图片 Glide.with(this) .load(thumbnailUrls.get(i)) .placeholder(R.drawable.default_thumbnail) .error(R.drawable.error_thumbnail) .override(thumbnailSize, thumbnailSize) .centerCrop() .into(thumbnail); ``` - 使用 Glide 库高效加载网络图片 - 设置占位图和错误图 - 精确控制图片尺寸避免内存浪费 - 中心裁剪保持图片比例 #### 4. 点击事件处理 ```java // 缩略图点击播放对应视频 thumbnail.setOnClickListener(v -> { playVideo(videoUrls.get(position)); }); ``` - 每个缩略图绑定对应的视频 URL - 点击时调用视频播放方法 - 使用 final position 确保事件绑定正确 ### 完整工作流程 1. **布局初始化**:XML 定义 4×2 的网格布局 2. **数据加载**:从 API 或本地获取缩略图和视频 URL 3. **动态创建**:在运行时创建 ImageView 并设置布局参数 4. **图片加载**:使用 Glide 异步加载和缓存缩略图 5. **事件绑定**:为每个缩略图添加点击播放事件 6. **视频播放**:点击时在 VideoView 中播放对应视频 ### 优化建议 1. **分页加载**:当缩略图超过 8 张时实现分页 2. **内存管理**:在 onDestroy 中清理 Glide 资源 3. **网络检测**:添加网络状态检查 4. **占位图优化**:使用更美观的占位设计 5. **响应式布局**:根据屏幕方向动态调整列数 ```java // 响应屏幕方向变化 @Override public void onConfigurationChanged(Configuration newConfig) { super.onConfigurationChanged(newConfig); addThumbnailsToGrid(); // 重新布局 } ```
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值