您需要实现一个适配器模式来填充列表视图。在您的情况下,您可以创建一个自定义适配器类并扩展 BaseAdapter 并实现其所有方法。模式是这样的。
MainActivity.java
public class MainActivity extends Activity {
private ListView listView;
private CustomAdapter adapter;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
listView = findViewById(android.R.id.list);
}
private class ImageDownloader extends AsyncTask<String, Void, Bitmap> {
@Override
protected Bitmap doInBackground(String... strings) {
try {
return downloadBitmap(params[0]);
} catch (ClientProtocolException e) {
return null;
} catch (Exception e) {
return null;
}
}
@Override
protected void onPostExecute(Bitmap bitmap) {
adapter = new CustomAdapter(bitmap);
listView.setAdapter(adapter);
super.onPostExecute(bitmap);
}
}
private class CustomAdapter extends BaseAdapter {
private Bitmap bitmap;
private LayoutInflater inflater = null;
class ViewHolder {
ImageView image;
}
public CustomAdapter(Bitmap bitmap) {
this.bitmap = bitmap;
inflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
@Override
public int getCount() {
return 0;
}
@Override
public Object getItem(int i) {
return null;
}
@Override
public long getItemId(int i) {
return 0;
}
@Override
public View getView(int i, View convertView, ViewGroup parent) {
final ViewHolder holder;
if(convertView == null) {
convertView = inflater.inflate(R.layout.list_item, parent, false);
holder.image = convertView.findViewById(R.id.imageView);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.image.setImageBitmap();
return convertView;
}
}
}
主要的.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ListView
android:id="@android:id/list"
android:layout_width="match_parent"
android:layout_height="match_parent"
/>
</LinearLayout>
list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<ImageView
android:id="@+id/imageView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
/>
</LinearLayout>
但是,当您将许多图像加载到列表视图中时,请创建一个 ArrayList 并将其发送到 listAdapter