更改图像视图源的最佳方法是什么?

What is the best way to change the source of an imageview?

我有一个图像视图,其中包含一个 png 文件。我想根据 4 个不同的事件(4 个不同的 png)更改此 imageview 的来源。 目前我正在使用 imageView.setImageResource 更改源,但这有延迟并会导致很多 Choreographer 警告。 有更好的方法吗?

你可以有 4 个 imageView 而不是一个,它们已经加载了你的 4 张图像,并调整这些 imageView 的可见性与哪些图像必须可见有关。

像这样,您不需要在执行期间更改任何 imageView 的源(仅更改可见性),并且会摆脱 loading/decoding 时间。

你可以试试这个库http://square.github.io/picasso/来加载图像

使用像 Picasso 或 Glide 这样的库。 它们都有非常简单的语法,并且会在单独的线程中加载图像,因此 UI 线程不会发生延迟。

查看图书馆

https://github.com/bumptech/glide

https://github.com/square/picasso

有更多的图像加载库,但这些可能是最容易使用的。

您可以将四个 ImageView 叠加在一起,然后根据您要显示的内容更改可见性。将图片加载到内存不会有延迟,因为它们都已经存在了。只要确保图片不会太占用内存即可

代码:

if (something)
    imageview1.setVisibility(View.VISIBLE);
else if (something)
    imageview2.setVisibility(View.GONE);

RelativeLayout 默认将视图堆叠在一起。在线性布局中设置 visibility.gone 也可能使视图 "stack"。 XML:

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent" android:layout_height="match_parent">

    <ImageView
        android:id="@+id/pic1"
        android:layout_width="100dp"
        android:layout_height="100dp" 
        android:src="@drawable/pic1"
        android:visibility="visible"
        android:contentDescription="default picture"/>
    <ImageView
        android:id="@+id/pic2"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/pic2"
        android:visibility="invisible"
        android:contentDescription="pic2"/>
    <ImageView
        android:id="@+id/pic3"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/pic3"
        android:visibility="invisible"
        android:contentDescription="pic3"/>

    <ImageView
        android:id="@+id/pic4"
        android:layout_width="100dp"
        android:layout_height="100dp"
        android:src="@drawable/pic4"
        android:visibility="invisible"
    android:contentDescription="pic4"/>
</RelativeLayout>