我有一个Android应用程序,我需要从服务器检索图像,并且必须将它们显示到网格视图中有标题。所以请任何人都可以帮助我如何在android中执行此任务。
答案 0 :(得分:2)
如果您使用URL来从服务器加载图像,那么您可以使用Picasso。
使用Picasso
- >
1)首先在built.gradle中的依赖项中添加compile 'com.squareup.picasso:picasso:2.5.2'
。
2)在网格适配器java文件中添加导入"com.squareup.picasso.Picasso;"
。
3)现在在适配器文件中添加"Picasso.with(context).load(pImage[position]).into(imageView);"
(从服务器数据加载网格)。
compileSdkVersion 23
buildToolsVersion "23.0.2"
dependencies {
compile fileTree(dir: 'libs', include: ['*.jar'])
testCompile 'junit:junit:4.12'
compile 'com.android.support:appcompat-v7:23.1.1'
compile 'com.android.support:design:23.1.1'
compile 'com.squareup.picasso:picasso:2.5.2'
}
现在适配器文件在getView方法中(注意po
是全局变量):
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
po = position;
View gridView;
if (convertView == null) {
gridView = inflater.inflate(R.layout.dashboard_inner, null);// set image based on selected text
} else {
gridView = (View) convertView;
}
imageView = (ImageView) gridView.findViewById(R.id.grid_item_image);
TextView textView1 = (TextView)gridView.findViewById(R.id.grid_item_text1);
textView1.setText(pName[position]);
TextView textView2 = (TextView) gridView.findViewById(R.id.grid_item_text2);
textView2.setText(pPrice[position]);
textView2.setPaintFlags(textView2.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
TextView textView3 = (TextView) gridView.findViewById(R.id.grid_item_text3);
textView3.setText(pSprice[position]);
TextView textView4 = (TextView) gridView.findViewById(R.id.grid_item_text4);
textView4.setText(pOffer[position]);
Picasso.with(context).load(pImage[position]).into(imageView);
return gridView;
}
答案 1 :(得分:1)
这可以通过以下步骤完成:
BaseAdapter
,创建用于存储图像和创建视图的自定义适配器。自己实现所需的功能。notifyDataSetChanged()
GridView
编辑好的,这是一个基本的概念证明:
活动(加载程序可以onCreate
方式启动):
public class MyActivity extends Activity implements LoaderManager.LoaderCallbacks<ArrayList<Drawable>> {
//other stuff
@Override
public Loader<ArrayList<Drawable>> onCreateLoader(int id, Bundle args) {
return new ImageLoader(this);
}
@Override
public void onLoadFinished(Loader<ArrayList<Drawable>> loader, ArrayList<Drawable> data) {
myAdapter.pushData(data);
}
@Override
public void onLoaderReset(Loader<ArrayList<Drawable>> loader) {
}
}
<强>装载机强>:
public class ImageLoader extends AsyncTaskLoader<ArrayList<Drawable>> {
public ImageLoader(Context context) {
super(context);
}
@Override
public ArrayList<Drawable> loadInBackground() {
//load the stuff
return data;
}
@Override
protected void onStartLoading() {
if (data != null) {
deliverResult(data);
}
if (takeContentChanged() || data == null) {
forceLoad();
}
}
}
<强>适配器强>:
public class MyAdapter extends BaseAdapter {
ArrayList<Drawable> data = new ArrayList<>();
//other functions
public void pushData(ArrayList<Drawable> data){
this.data = data;
notifyDataSetChanged();
}
}