当我在ListView中使用Glide时,为什么图像的大小会令人困惑?

时间:2019-05-29 07:16:50

标签: java android android-glide

我想用Internet图像实现ListView。我使用Glide在列表项中加载图像,但是发现图像的大小总是令人困惑。我写了一些测试代码来重新出现这个问题。

起初这很正常。 at first 但是,当我快速滑动ListView时,图像的大小变得令人困惑。 test1 test2

如何在不修改glide源代码的情况下解决问题?

MainActivity.java

public class MainActivity extends AppCompatActivity {

    private String[] urls = new String[]{"https:......"};
    //urls of images.

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        ListView listView = findViewById(R.id.list_view);
        final SparseArray<String> sparseArray = new SparseArray<>();
        listView.setAdapter(new BaseAdapter() {
            @Override
            public int getCount() {
                return 100000;
            }

            @Override
            public Object getItem(int i) {
                String url = sparseArray.get(i);
                if(url == null){
                    url = urls[(int)(Math.random() * urls.length)];
                    sparseArray.put(i,url);
                }
                return url;
            }

            @Override
            public long getItemId(int i) {
                return i;
            }

            @Override
            public View getView(int i, View view, ViewGroup viewGroup) {
                if(view == null){
                    view = View.inflate(getBaseContext(),R.layout.list_view_item_image,null);
                }
                ImageView imageView = view.findViewById(R.id.image_view);
                Glide.with(getBaseContext())
                        .load((String)getItem(i))
                        .into(imageView);
                return view;
            }
        });
    }
}

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity">

    <ListView
        android:id="@+id/list_view"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        />

</android.support.constraint.ConstraintLayout>

list_view_item_image.xml

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

    <ImageView
        android:id="@+id/image_view"
        android:adjustViewBounds="true"
        android:maxHeight="200dp"
        android:maxWidth="200dp"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content" />

</LinearLayout>

0 个答案:

没有答案