滚动时GridView图像正在改变位置

时间:2015-09-04 15:27:37

标签: android

我正在从服务器加载图像以及文本并在gridview中显示它们,我正在使用基础适配器来填充网格。以下是适配器的代码:

   package com.erc.test;

    import java.util.ArrayList;

    import android.content.Context;
    import android.view.LayoutInflater;
    import android.view.View;
    import android.view.ViewGroup;
    import android.widget.BaseAdapter;
    import android.widget.TextView;
    public class CustomGrid2 extends BaseAdapter{
        private Context mContext;
        private final ArrayList<String> web;
        private final ArrayList<String> Imageid;
          public CustomGrid2(Context c,ArrayList<String> web, ArrayList<String> imageId ) {
              mContext = c;
              this.Imageid = imageId;
              this.web = web;
          }

          public void removeItem(int position){
              web.remove(position);
              Imageid.remove(position);
              notifyDataSetChanged();
         }


          public void clearitems(){
              web.clear();
              Imageid.clear();
              notifyDataSetChanged();
         }

        @Override
        public int getCount() {
          // TODO Auto-generated method stub
          return web.size();
        }
        @Override
        public Object getItem(int position) {
          // TODO Auto-generated method stub
          return null;
        }
        @Override
        public long getItemId(int position) {
          // TODO Auto-generated method stub
          return 0;
        }
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
          // TODO Auto-generated method stub

        /////////////////////////////////// 
            View grid;
            if (convertView == null) {  // if it's not recycled, initialize some attributes
                LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(     Context.LAYOUT_INFLATER_SERVICE );
                grid = inflater.inflate(R.layout.grid_single, parent, false);
            } else {
                grid = (View) convertView;
            }
            TextView text = (TextView)grid.findViewById(R.id.textView1);
            text.setText(web.get(position));
            RoundedImageView image = (RoundedImageView)grid.findViewById(R.id.grid_image);
            image.setPlaceholderImage(R.drawable.ic_launcher);
            image.setImageUrl(Imageid.get(position));
          //  image.setImageDrawable();
            return grid;
       ////////////////////////////////////////////////////     


        }
    }

在我的主要课程中,我正在做以下事情:

package com.erc.test;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.net.URL;
import java.util.ArrayList;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.util.EntityUtils;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.content.Intent;
import android.graphics.drawable.Drawable;
import android.net.ParseException;
import android.os.AsyncTask;
import android.os.Bundle;
import android.os.StrictMode;
import android.util.Log;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
import android.widget.ProgressBar;
import android.widget.Toast;


public class Categories extends Activity {
    HttpResponse response;
    HttpEntity entity;
    HttpClient httpclient;
    HttpPost httppost;
    GridView grid;
    ProgressBar pb;
    CustomGrid2 adapter;
       Drawable[] dd=null;
        ArrayList<String> actorsList;
        ArrayList<String> title;
        JSONArray jarray;
    ArrayList<String> namearray= new ArrayList<String>();    
    ArrayList<Drawable> imagearray= new ArrayList<Drawable>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        // TODO Auto-generated method stub
        super.onCreate(savedInstanceState);
        setContentView(R.layout.categories);

        grid=(GridView)findViewById(R.id.gridView1);
        pb=(ProgressBar)findViewById(R.id.progressBar1);
         actorsList = new ArrayList<String>();
           title = new ArrayList<String>();
        new ProgressTask().execute();

    }


    class ProgressTask extends AsyncTask <Void,Void,Void>
    {

        @Override
        protected void onPreExecute()
        {
            pb.setVisibility(View.VISIBLE);
        }

        @Override
        protected Void doInBackground(Void... arg0) {
            // TODO Auto-generated method stub

            StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
            StrictMode.setThreadPolicy(policy);
            try {

                //------------------>>
                HttpGet httppost = new HttpGet("http://www.page.com/folder/file.php?userid=2&client=android&sandbox=0&language=en&format=json");
                HttpClient httpclient = new DefaultHttpClient();
                HttpResponse response = httpclient.execute(httppost);

                // StatusLine stat = response.getStatusLine();
                int status = response.getStatusLine().getStatusCode();

                if (status == 200) {
                    HttpEntity entity = response.getEntity();
                    String data = EntityUtils.toString(entity);


                    JSONObject jsono = new JSONObject(data);
                     jarray = jsono.getJSONArray("categories");


                }

                //------------------>>

            } catch (ParseException e1) {
            //  Toast.makeText(getBaseContext(), e1.toString(),Toast.LENGTH_LONG).show();

              // e1.printStackTrace();
            } catch (IOException e) {
                // e.printStackTrace();
                //Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
            } catch (JSONException e) {
                // e.printStackTrace();
                //Toast.makeText(getBaseContext(), e.toString(),Toast.LENGTH_LONG).show();
            }

            return null;
        }

        @Override
        protected void onPostExecute(Void result) 
        {
            try
            {
              for (int i = 0; i < jarray.length(); i++) {
                    JSONObject object = jarray.getJSONObject(i);

                  //  Actors actor = new Actors();
                    actorsList.add(object.getString("picture").replace("https","http"));
                    title.add(object.getString("name"));}
              }         
                   catch(Exception ex)
                   {
                       Toast.makeText(getBaseContext(), ex.toString(),Toast.LENGTH_LONG).show();
                   }
              //      Log.d("title is",object.getString("image"));

//                  adapter = new CustomGrid2(MainActivity.this, title, actorsList);
            //  grid.setAdapter(adapter);
                 //   actor.setImage(object.getString("image"));

                 //   actorsList.add(actor);



            pb.setVisibility(View.GONE);
            adapter = new CustomGrid2(Categories.this, title, actorsList);
            grid.setAdapter(adapter);
            adapter.notifyDataSetChanged();


//          grid.setOnItemClickListener(new OnItemClickListener() {
//
//              @Override
//              public void onItemClick(AdapterView<?> arg0, View arg1,
//                      int arg2, long arg3) {
//                  // TODO Auto-generated method stub
//              String id=String.valueOf(arg2+1);
//              String category_name=namearray.get(arg2);
//              Intent intent = new Intent(Categories.this, Subcategories.class);
//              Bundle b = new Bundle();
//              b.putString("ID",id); //Your id
//              b.putString("Name",category_name);
//              intent.putExtras(b); //Put your id to your next Intent
//              startActivity(intent);
//              
//              }
//          });




        }
    }

//    private static String convertStreamToString(InputStream is)
//      {
//
//
//      BufferedReader reader = new BufferedReader(new InputStreamReader(is));
//      StringBuilder sb = new StringBuilder();
//      String line = null;
//      try
//      {
//
//      while ((line = reader.readLine()) != null) {
//        sb.append(line + "\n");
//      }
//      }catch(IOException e)
//      {
//
//      }
//      finally
//      {
//          try{
//              is.close();
//          }catch(IOException e)
//          {
//              
//          }
//          }return sb.toString();
//
//
//
//      }

}

在下面的课程中,我给imageview一个圆形的形状,然后从url下载图像:

package com.erc.test;

import java.io.BufferedInputStream;
import java.io.InputStream;
import java.net.URL;
import java.net.URLConnection;

import org.apache.http.util.ByteArrayBuffer;

import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.Bitmap.Config;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.PorterDuff.Mode;
import android.graphics.PorterDuffXfermode;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.AsyncTask;
import android.util.AttributeSet;
import android.widget.ImageView;



    public class RoundedImageView extends ImageView {
        private Drawable placeholder, image;

        public RoundedImageView(Context context) {
            super(context);
            // TODO Auto-generated constructor stub
        }

        public RoundedImageView(Context context, AttributeSet attrs) {
            super(context, attrs);
        }

        public RoundedImageView(Context context, AttributeSet attrs, int defStyle) {
            super(context, attrs, defStyle);
        }

        @Override
        protected void onDraw(Canvas canvas) {

            Drawable drawable = getDrawable();

            if (drawable == null) {
                return;
            }

            if (getWidth() == 0 || getHeight() == 0) {
                return; 
            }
            Bitmap b =  ((BitmapDrawable)drawable).getBitmap() ;
            Bitmap bitmap = b.copy(Bitmap.Config.ARGB_8888, true);

            int w = getWidth(), h = getHeight();


            Bitmap roundBitmap =  getCroppedBitmap(bitmap, w);
            canvas.drawBitmap(roundBitmap, 0,0, null);

        }

         public void setPlaceholderImage(Drawable drawable) {
                placeholder = drawable;
                if (image == null) {
                    setImageDrawable(placeholder);
                }
            }
            public void setPlaceholderImage(int resid) {
                placeholder = getResources().getDrawable(resid);
                if (image == null) {
                    setImageDrawable(placeholder);
                }
            }

            public void setImageUrl(String url) {
                DownloadTask task = new DownloadTask();  
                task.execute(url);
            }

            private class DownloadTask extends AsyncTask<String, Void, Bitmap> {

                @Override
                protected Bitmap doInBackground(String... params) {
                    String url = params[0];
                    try {
                        URLConnection conn = (new URL(url)).openConnection();
                        InputStream is = conn.getInputStream();
                        BufferedInputStream bis = new BufferedInputStream(is);

                        ByteArrayBuffer baf = new ByteArrayBuffer(50); 
                        int current = 0;
                        while ((current=bis.read()) != -1) {
                            baf.append((byte)current);
                        }

                        byte[] imageData = baf.toByteArray();
                        return BitmapFactory.decodeByteArray(imageData, 0, imageData.length);

                    } catch (Exception e) {
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(Bitmap result) {
                    image = new BitmapDrawable(result);
                    if (image != null) {
                        setImageDrawable(image);
                    }
                }



            }

            public Bitmap getCroppedBitmap(Bitmap bmp, int radius) {
                Bitmap sbmp;
                if(bmp.getWidth() != radius || bmp.getHeight() != radius)
                    sbmp = Bitmap.createScaledBitmap(bmp, radius, radius, false);
                else
                    sbmp = bmp;
                Bitmap output = Bitmap.createBitmap(sbmp.getWidth(),
                        sbmp.getHeight(), Config.ARGB_8888);
                Canvas canvas = new Canvas(output);

                final int color = 0xffa19774;
                final Paint paint = new Paint();
                final Rect rect = new Rect(0, 0, sbmp.getWidth(), sbmp.getHeight());

                paint.setAntiAlias(true);
                paint.setFilterBitmap(true);
                paint.setDither(true);
                canvas.drawARGB(0, 0, 0, 0);
                paint.setColor(Color.parseColor("#BAB399"));
                canvas.drawCircle(sbmp.getWidth() / 2+0.7f, sbmp.getHeight() / 2+0.7f,
                        sbmp.getWidth() / 2+0.1f, paint);
                paint.setXfermode(new PorterDuffXfermode(Mode.SRC_IN));
                canvas.drawBitmap(sbmp, rect, rect, paint);


                        return output;
            }
        }

问题是当我滚动网格时图像改变位置,请问有什么帮助吗?

0 个答案:

没有答案