如何将图片加载到网格视图?

3
我有一个包含图片链接的数据库,如何从服务器下载这些图片并在网格视图中显示它们。 我已经查看了这段代码here,有人能帮我吗?
2个回答

3

2
我在HomeActivity.java中使用了以下函数。
  public void loadGallery() throws Exception{
          String jBannerString = executeHttpGet("http://sujanmaharjan.com.np/joomla/index.php?option=com_atomicongallery&folder=root");
          //  String jBannerString = executeHttpGet("http://localhost/new/himalmag/index.php?option=com_gk");

                jBannerString = "{'earthquakes':" + jBannerString;
                jBannerString = jBannerString + "}";

                        JSONArray r_jsBanner = null;
                        try
                        {
                        jObject = new JSONObject(jBannerString);
                        r_jsBanner = jObject.getJSONArray("earthquakes");    
                        id = new String[r_jsBanner.length()];
                        thumb_image = new String[r_jsBanner.length()];
                        main_image = new String[r_jsBanner.length()];
                        for (int i =0; i < r_jsBanner.length() ; i++){
                            JSONObject arGallery = r_jsBanner.getJSONObject(i);  
                            id[i]= i+""; 
                            thumb_image[i]=arGallery.getString("thumbnail"); 
                            main_image[i]=arGallery.getString("url"); 

                        }                    
                        } catch(Exception es){         
                        }

            Message myMessage=new Message();
            Bundle resBundle = new Bundle();
            resBundle.putString("status", "SUCCESS");
            myMessage.obj=resBundle;
            handlerGallery.sendMessage(myMessage);
        }
        private Handler handlerGallery = new Handler() {

            public void handleMessage(Message msg) {                
            //   dialog.dismiss();
                GkTab.gkTab.progressBar.setVisibility(View.GONE);
                 GridView gridGallery = (GridView)findViewById(R.id.gridGallery);
                 gridGallery.setAdapter(new ImageAdapter(HomeActivity.this,R.layout.gridview , thumb_image,1));
                 gridGallery.setOnItemClickListener(
                         new OnItemClickListener() 
                         {                              
                             public void onItemClick(AdapterView<?> arg0, View arg1, int position , long id) { 

                                     Intent myintent =new Intent(getApplicationContext(), LayoutGallery.class);
                                     myintent.putExtra("position",position);
                                     myintent.putExtra("stringurl", main_image);
                                     startActivity(myintent);

                                 }
                         });
            }
        };
      public String executeHttpGet(String httpUrl) throws Exception {

            BufferedReader in = null;
            StringBuffer sb = new StringBuffer("");
            try {
             /* HttpParams httpParameters = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpParameters, 1000); // Connection timeout 
                HttpConnectionParams.setSoTimeout(httpParameters, 1000); // Socket timeout
    */
                HttpClient client = new DefaultHttpClient();
                HttpGet request = new HttpGet();
                request.setURI(new URI(httpUrl));
                HttpResponse response = client.execute(request);
                in = new BufferedReader
                (new InputStreamReader(response.getEntity().getContent()));

                String line = "";
                String NL = System.getProperty("line.separator");
                while ((line = in.readLine()) != null) {
                    sb.append(line + NL);
                }
                in.close(); 
               // parse(sb.toString());
                } 
            finally {
                if (in != null) {
                    try {
                        in.close();
                        } catch (IOException e) {
                        e.getMessage();
                    }                  
                }
            }

            return sb.toString();
        }

创建新的Activity LayoutGallery.java。
public class LayoutGallery extends Activity {
CustomGallery galleryPictureImage;
/** Called when the activity is first created. */
@Override
    public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    //makes full screen and takes away title bar
    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,WindowManager.LayoutParams.FLAG_FULLSCREEN);
    //
    Display display = getWindowManager().getDefaultDisplay();
     int width = display.getWidth();
     int height = width*3/4;

    setContentView(R.layout.gallerylayout);
    Intent i = getIntent();
    // Receiving the Data
    int position= i.getIntExtra("position", 0);
    String[] stringurl = i.getStringArrayExtra("stringurl");
    galleryPictureImage = (CustomGallery)findViewById(R.id.picturegallerynew);
    galleryPictureImage.setSpacing(50);
    galleryPictureImage.setAdapter(new LazyGalleryAdapter(LayoutGallery.this,stringurl,null,width,height,1));
    galleryPictureImage.setSelection(position);

    }


}

创建CustomGallery.java文件
import android.content.Context;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Gallery;

public class CustomGallery extends Gallery{

    public CustomGallery(Context context, AttributeSet attrs) {
        super(context, attrs);
        // TODO Auto-generated constructor stub
    }

    @Override
    public boolean onFling(MotionEvent e1, MotionEvent e2, float velocityX, float velocityY) {
      return super.onFling(e1, e2, 0, velocityY);
    }

}

创建 gallerylayout.xml 文件
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout
  xmlns:android="http://schemas.android.com/apk/res/android"
  android:layout_width="fill_parent"
  android:layout_height="fill_parent"
  android:orientation="horizontal"
  >
        <com.np.sujanmaharjan.gk.CustomGallery
                xmlns:android="http://schemas.android.com/apk/res/android"
                android:id="@+id/picturegallerynew"
                android:fadingEdge="none" 
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                android:layout_gravity="center"
                android:theme="@android:style/Theme.Black.NoTitleBar.Fullscreen" />

</LinearLayout>     

创建LazyGalleryAdapter.java文件。
package com.np.sujanmaharjan.gk;


import android.app.Activity;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.ViewGroup.LayoutParams;
import android.widget.BaseAdapter;
import android.widget.Gallery;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;


public class LazyGalleryAdapter extends BaseAdapter{

    private Activity activity;
    private String[] data;
    private static LayoutInflater inflater=null;
    private ProgressBar mProgressBar;
    public ImageLoader imageLoader; 
    public int width;
    public int height;
    public int imgwidth;
    private String[] caption;
    public int widthStatus=0;
    public LazyGalleryAdapter(Activity a, String[] d) {
        activity = a;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());

    }
    public LazyGalleryAdapter(Activity a, String[] d,String[] c,int wid,int h,int mainGallery) {
        activity = a;
        caption= c;
        data=d;
        inflater = (LayoutInflater)activity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        imageLoader=new ImageLoader(activity.getApplicationContext());
        width=wid;
        height=h;
        if(mainGallery==1)
            widthStatus=1; // for main gallery of picture

    }

    public int getCount() {
        return data.length;
    }

    public Object getItem(int position) {
        return position;
    }

    public long getItemId(int position) {
        return position;
    }

    public static class ViewHolder{
        public TextView text;
        public ImageView image;
        public ProgressBar progressBar;
        public LinearLayout ProgressContain;
        public LinearLayout imageCaptionLayout;
    }

    public View getView(int position, View convertView, ViewGroup parent) {
        View vi=convertView;
        ViewHolder holder;
        if(convertView==null){
            vi = inflater.inflate(R.layout.gallerypage, null);
            holder=new ViewHolder();
            holder.image=(ImageView)vi.findViewById(R.id.imageGallery);
            holder.progressBar = (ProgressBar)vi.findViewById(R.id.idProgressBar);
            holder.ProgressContain = (LinearLayout)vi.findViewById(R.id.idProgressContain);
            holder.imageCaptionLayout = (LinearLayout)vi.findViewById(R.id.imageCaptionLayout); 
            holder.text =(TextView)vi.findViewById(R.id.imageCaption); 

                 imgwidth=width;
                 holder.image.getLayoutParams().width=imgwidth; 
                 holder.image.getLayoutParams().height=imgwidth*2/3; 
                 holder.image.setScaleType(ImageView.ScaleType.FIT_XY);
                 holder.ProgressContain.getLayoutParams().width=imgwidth;
                 holder.ProgressContain.getLayoutParams().height=imgwidth*2/3;
                 holder.ProgressContain.setBackgroundColor(0xFF414141);           

            vi.setTag(holder);
        }
        else
            holder=(ViewHolder)vi.getTag();

            if(caption[position].equals("")){
                holder.text.setText("no caption"); 
                holder.text.setVisibility(View.INVISIBLE);
                holder.imageCaptionLayout.getBackground().setAlpha(0);
            }
            else{
                holder.imageCaptionLayout.getBackground().setAlpha(100);
                holder.text.setText(caption[position]+"  "); 
                holder.text.setVisibility(View.VISIBLE);
            }

        holder.image.setTag(data[position]);
        imageLoader.DisplayImage(data[position], activity, holder.image,holder.ProgressContain);

        return vi;
    }

}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接