我确信这不是一个新问题。不幸的是,在为这项活动争取了 20 多个小时后,我仍然找不到解决方案。你能帮我一把吗?我将非常感激。
嘿,是我的问题。我想将来自不同 url 的图像显示到 girdView 布局。但是,我的代码不起作用,因此屏幕什么也没有显示。你能帮我解决这个问题吗?
下面是我的 MainActivity 类
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
String [] imgUrlList = {
"http://image.tmdb.org/t/p/w500/cGOPbv9wA5gEejkUN892JrveARt.jpg",
"http://image.tmdb.org/t/p/w500/6FxOPJ9Ysilpq0IgkrMJ7PubFhq.jpg",
"http://image.tmdb.org/t/p/w500/z09QAf8WbZncbitewNk6lKYMZsh.jpg",
"http://image.tmdb.org/t/p/w500/kqjL17yufvn9OVLyXYpvtyrFfak.jpg"
};
mMovieAdapter = new MyAdapter(this, imgUrlList);
GridView gridview = (GridView) findViewById(R.id.gridView);
gridview.setAdapter(mMovieAdapter);
}
public class MyAdapter extends ArrayAdapter<String>{
private final Activity context;
private final String[] imgUrlList;
public MyAdapter (Activity context, String[] imgUrlList){
super(context, R.layout.image_item);
this.context = context;
this.imgUrlList = imgUrlList;
}
public View getView (int position, View view, ViewGroup parent){
LayoutInflater inflater = context.getLayoutInflater();
View rootView = inflater.inflate(R.layout.image_item, null, true);
new DownloadImageTask((ImageView) rootView.findViewById(R.id.imageItem)).execute(imgUrlList[position]);
ImageView imageView = (ImageView) rootView.findViewById(R.id.imageItem);
imageView.setImageURI(Uri.parse(imgUrlList[position]));
return rootView;
}
}
private class DownloadImageTask extends AsyncTask <String, Void, Bitmap>{
ImageView poster;
public DownloadImageTask(ImageView poster) {
this.poster = poster;
}
protected Bitmap doInBackground(String... urls){
String imageUrls = urls[0];
Bitmap moviePoster = null;
try {
InputStream in = new java.net.URL(imageUrls).openStream();
moviePoster = BitmapFactory.decodeStream(in);
} catch (Exception e) {
Log.e("Error", e.getMessage());
e.printStackTrace();
}
return moviePoster;
}
@Override
protected void onPostExecute(Bitmap result) {
poster.setImageBitmap(result);
}
}
下面是我的 xml (activity_main) 文件
<GridView
android:id="@+id/gridView"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:columnWidth="185dp"
android:numColumns="auto_fit"/>
我也有一个 imageView 文件调用 image_item