Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
834 views
in Technique[技术] by (71.8m points)

android - GridView Images are changing postion when scrolling

I'm loading images from server along with a text and displaying them in a gridview, I'm using a base adapter to fill the grid. Here is the code of the adapter:

   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;
       ////////////////////////////////////////////////////     


        }
    }

In my main class I'm doing the following :

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 + "
");
//      }
//      }catch(IOException e)
//      {
//
//      }
//      finally
//      {
//          try{
//              is.close();
//          }catch(IOException e)
//          {
//              
//          }
//          }return sb.toString();
//
//
//
//      }

}

And in the following class I give the imageview a circular shape and I download the image from 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 se

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...