gpt4 book ai didi

java - 轻松创建 "loading"动画

转载 作者:行者123 更新时间:2023-11-29 21:03:35 25 4
gpt4 key购买 nike

我有一个 android listView,每个项目都有一个图像。加载图像需要一段时间。如何在每次加载图像时添加“加载”动画?

我应该使用 .gif 吗?或者创建我自己的动画并在 onPostExecute() 上停止它?

如果我使用“picasso”,我该怎么做,因为所有异步任务对开发人员来说都是黑盒,我无法停止任何动画?

最佳答案

使用以下代码:

主 Activity .java

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

ArrayList<HashMap<String, String>> itemsList = new ArrayList<HashMap<String, String>>();

ListView listView = (ListView) findViewById(R.id.listView);

for (int i = 0; i < 5; i++) {

// creating new HashMap
HashMap<String, String> map = new HashMap<String, String>();

// adding each child node to HashMap key =&gt; value
map.put("key1", "value1");
map.put("key2", "value2");

// adding HashList to ArrayList
itemsList.add(map);
}

ListAdapter listAdapter = new ListAdapter(this, itemsList);
listView.setAdapter(listAdapter);
}

list_row.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:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true"
android:src="@drawable/ic_launcher" />

<ProgressBar
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/progressBar"
android:layout_toEndOf="@+id/imageView"
android:layout_alignParentTop="true"
android:layout_alignParentLeft="true"
android:layout_alignParentStart="true" />
</RelativeLayout>

ListAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
if (convertView == null)
vi = inflater.inflate(R.layout.list_row, null);

ImageView imageView = (ImageView) vi.findViewById(R.id.imageView);
final ProgressBar progressBar = (ProgressBar) vi.findViewById(R.id.progressBar);

//This line shows progressBar again for recycled view
progressBar.setVisibility(View.VISIBLE);

Picasso.with(activity.getApplicationContext()).load(imagePath).resize(100, 100)
.into(imageView, new Callback() {
@Override
public void onSuccess() {
progressBar.setVisibility(View.GONE);
}

@Override
public void onError() {
//error
}
});

return vi;
}

不要忘记为 Picasso 回调添加导入

import com.squareup.picasso.Callback;

关于java - 轻松创建 "loading"动画,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25218853/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com