gridview中的OnItemClickListener重复

时间:2014-09-15 12:15:54

标签: android gridview

我是android的新手,并尝试使用选定的元素创建gridview。

如果我使用OnItemClickListener并更改,例如视图的alpha它会改变2个图像而不是1个。 我不知道问题出在哪里。请提出任何建议:)

MainActivity.java

package com.example.collage;

import java.io.BufferedReader;
import java.io.InputStreamReader;
import java.net.URL;
import java.net.UnknownHostException;
import java.util.ArrayList;
import java.util.concurrent.ExecutionException;

import org.json.simple.JSONArray;
import org.json.simple.JSONObject;
import org.json.simple.parser.JSONParser;
import org.json.simple.parser.ParseException;

import android.accounts.NetworkErrorException;
import android.app.Activity;
import android.content.Intent;
import android.os.AsyncTask;
import android.os.Bundle;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.ArrayAdapter;
import android.widget.Button;
import android.widget.GridView;
import android.widget.TextView;
import android.widget.Toast;

public class MainActivity extends Activity implements OnClickListener {

    static String CLIENT_ID = "1c77d0e90073461a8d16e70eb040e407";
    String user_id;
    ArrayList<Photo> list;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        Button button1 = (Button) findViewById(R.id.button1);
        button1.setOnClickListener(this);

    }

    @Override
    public void onClick(View v) {
        // TODO Auto-generated method stub
        TextView edittext1 = (TextView) findViewById(R.id.editText1);
        if (edittext1.getText().toString().length() == 0) {
            Toast.makeText(getApplicationContext(), "Введите логин",
                    Toast.LENGTH_SHORT).show();
        } else {
            String url = "https://api.instagram.com/v1/users/search?q="
                    + edittext1.getText().toString() + "&client_id="
                    + CLIENT_ID;

            MyTask response = new MyTask();
            try {
                user_id = response.execute(url).get();

                if (user_id != "") {
                    String url2 = "https://api.instagram.com/v1/users/"
                            + user_id + "/media/recent/?client_id=" + CLIENT_ID;
                    PhotoList photos = new PhotoList();
                    list = photos.execute(url2).get();
                }

                Intent intent = new Intent(MainActivity.this,
                        Photo_picker.class);
                Photo_picker.setViews(Photo.getDrawable(list));
                startActivity(intent);
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }
        }

    }

    private String readUrl(String urlString) throws Exception {
        BufferedReader reader = null;
        try {
            URL url = new URL(urlString);
            reader = new BufferedReader(new InputStreamReader(url.openStream()));
            StringBuffer buffer = new StringBuffer();
            int read;
            char[] chars = new char[1024];
            while ((read = reader.read(chars)) != -1)
                buffer.append(chars, 0, read);

            return buffer.toString();
        } finally {
            if (reader != null)
                reader.close();
        }
    }

    class PhotoList extends AsyncTask<String, String, ArrayList<Photo>> {
        @Override
        // creating all user's photo without downloading
        protected ArrayList<Photo> doInBackground(String... params) {
            ArrayList<Photo> photos = new ArrayList<Photo>();
            try {

                JSONParser fp = new JSONParser();
                JSONObject jo = (JSONObject) fp.parse(readUrl(params[0]));
                JSONArray array = (JSONArray) jo.get("data");

                for (int i = 0; i < array.size(); i++) {
                    JSONObject data = (JSONObject) array.get(i);
                    data.toString();
                    if (!data.isEmpty()) {
                        JSONObject images = (JSONObject) data.get("images");
                        JSONObject likes = (JSONObject) data.get("likes");
                        long like = (long) likes.get("count");
                        System.out.print(like);
                        JSONObject low = (JSONObject) images
                                .get("low_resolution");
                        JSONObject thumbnail = (JSONObject) images
                                .get("thumbnail");
                        JSONObject standart = (JSONObject) images
                                .get("standard_resolution");
                        photos.add(new Photo((String) low.get("url"),
                                (String) thumbnail.get("url"),
                                (String) standart.get("url"), like));

                    }
                }
            } catch (NetworkErrorException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Ошибка в интернет соединении",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (ParseException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Неудалось загрузить страницу",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (UnknownHostException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(
                                getApplicationContext(),
                                "Ошибка в интернет соединении, проверьте подключение к интернету",
                                Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                System.out.print(e.toString());
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Неизвестная ошибка", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }
            return photos;
        }
    }

    class MyTask extends AsyncTask<String, String, String> { // getting an id of
                                                                // the user
        @Override
        protected String doInBackground(String... params) {
            String id = "";
            try {

                JSONParser fp = new JSONParser();
                JSONObject jo = (JSONObject) fp.parse(readUrl(params[0]));
                JSONObject data = (JSONObject) ((JSONArray) jo.get("data"))
                        .get(0);
                if (!data.isEmpty()) {
                    id = (String) data.get("id");
                } else {
                    Toast.makeText(getApplicationContext(),
                            "Логин не существует", Toast.LENGTH_SHORT).show();
                    return "";
                }

            } catch (NetworkErrorException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Ошибка в интернет соединении",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (ParseException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Неудалось загрузить страницу",
                                Toast.LENGTH_SHORT).show();
                    }
                });
            } catch (UnknownHostException e) {
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(
                                getApplicationContext(),
                                "Ошибка в интернет соединении, проверьте подключение к интернету",
                                Toast.LENGTH_SHORT).show();
                    }
                });

            } catch (Exception e) {
                System.out.print(e.toString());
                runOnUiThread(new Runnable() {
                    public void run() {
                        Toast.makeText(getApplicationContext(),
                                "Неизвестная ошибка", Toast.LENGTH_SHORT)
                                .show();
                    }
                });
            }
            return id;
        }
    }
}

Photo_picker.java

package com.example.collage;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Context;
import android.content.res.Configuration;
import android.graphics.Color;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.BaseAdapter;
import android.widget.GridView;
import android.widget.ImageView;
import android.widget.ListAdapter;

public class Photo_picker extends Activity {
    GridView gridview;
    static ArrayList<Drawable> images;

    public static void setViews(ArrayList<Drawable> images) {
        Photo_picker.images = images;
    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_photo_picker);
        gridview = (GridView) findViewById(R.id.gridView1_bir);
        gridview.setAdapter(new ImageAdapter(this, images));
        gridview.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
        gridview.setVerticalSpacing(4);
        gridview.setHorizontalSpacing(4);
        gridview.setBackgroundColor(Color.DKGRAY);
        gridview.setOnItemClickListener(new OnItemClickListener() {

            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                // TODO Auto-generated method stub
                view.setAlpha((float) 0.5);
            }
        });
    }

    public class ImageAdapter extends BaseAdapter implements ListAdapter {

        private ArrayList<Drawable> images;
        int height, width;

        public ImageAdapter(Context context, ArrayList<Drawable> images) {
            super();
            this.images = images;
            height = context.getResources().getDisplayMetrics().heightPixels;
            width = context.getResources().getDisplayMetrics().widthPixels;
        }

        public int getCount() {
            return images.size();

        }

        public long getItemId(int position) {

            return position;
        }

        public View getView(int position, View convertView, ViewGroup parent) {
            ImageView imageView;

            if (convertView == null) {
                imageView = new ImageView(Photo_picker.this);

                if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
                    imageView.setLayoutParams(new GridView.LayoutParams(
                            width / 2, height / 3));

                } else {
                    imageView.setLayoutParams(new GridView.LayoutParams(
                            width / 3, height / 2));

                }
                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                imageView.setPadding(0, 0, 0, 0);
                imageView.setFocusable(false);
                imageView.setFocusableInTouchMode(false);
                imageView.setClickable(false);
            } else {
                imageView = (ImageView) convertView;

            }
            imageView.setImageDrawable(images.get(position));
            return imageView;
        }

        @Override
        public Object getItem(int position) {
            // TODO Auto-generated method stub
            return null;
        }

    }

}

Photo.java

package com.example.collage;

import java.io.InputStream;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.ArrayList;
import java.util.Collections;
import java.util.concurrent.ExecutionException;

import android.graphics.drawable.Drawable;
import android.os.AsyncTask;

public class Photo implements Comparable<Photo> {

    private URL lowimage, thumbnail, standart, url;
    private long likes;
    static int NUM_PHOTO = 20;

    public Photo(String lowimage, String thumbnail, String standart, long likes) {
        this.likes = likes;
        try {
            this.lowimage = new URL(lowimage);
            this.thumbnail = new URL(thumbnail);
            this.standart = new URL(standart);
        } catch (MalformedURLException e) {

        }

    }

    private static ArrayList<Photo> createPopularList(ArrayList<Photo> photo) {
        ArrayList<Photo> popular;
        popular = new ArrayList<Photo>();
        Collections.sort(photo, Collections.reverseOrder());// descending order
        if (photo.size() < NUM_PHOTO) {
            popular.addAll(photo);
        } else {
            popular.addAll(photo.subList(0, NUM_PHOTO));
        }

        return popular;

    }

    public static ArrayList<Drawable> getDrawable(ArrayList<Photo> photo) {
        Download d = new Download();
        ArrayList<Drawable> list = new ArrayList<Drawable>();
        try {
            list = d.execute(createPopularList(photo)).get();
        } catch (InterruptedException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        } catch (ExecutionException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return list;
    }

    public URL getLowimage() {
        return lowimage;
    }

    public URL getThumbnail() {
        return thumbnail;
    }

    public URL getStandart() {
        return standart;
    }

    public long getLikes() {
        return likes;
    }

    @Override
    public int compareTo(Photo another) {
        return Long.compare(this.likes, another.getLikes());

    }

    static class Download
            extends
            AsyncTask<ArrayList<Photo>, ArrayList<Drawable>, ArrayList<Drawable>> {

        @Override
        protected ArrayList<Drawable> doInBackground(ArrayList<Photo>... params) {
            ArrayList<Drawable> views = new ArrayList<Drawable>();
            for (Photo p : params[0]) {
                views.add(LoadImageFromURL(p.getLowimage()));
            }
            return views;
        }

        private Drawable LoadImageFromURL(URL url) {
            try {
                InputStream is = (InputStream) url.getContent();
                Drawable d = Drawable.createFromStream(is, "src");
                return d;
            } catch (Exception e) {
                System.out.println(e);
                return null;
            }
        }

    }
}

PhotoPicker xml:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context=".MainActivity"
    android:background="#e5e5e5"
     >

    <GridView
        android:id="@+id/gridView1_bir"
        android:layout_width="fill_parent"
        android:layout_height="fill_parent"
        android:layout_marginLeft="0dp"
        android:columnWidth="160dp"
        android:gravity="center"
        android:horizontalSpacing="0dp"
        android:numColumns="auto_fit"
        android:stretchMode="columnWidth"
        android:verticalSpacing="0dp" />

</RelativeLayout>

mainActivity.xml文件:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    tools:context="${relativePackage}.${activityClass}" >

    <Button
        android:id="@+id/button1"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentBottom="true"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="132dp"
        android:minWidth="200dip"
        android:text="Давай коллаж" />

    <EditText
        android:id="@+id/editText1"
        android:inputType="textVisiblePassword|textNoSuggestions"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_above="@+id/button1"
        android:layout_centerHorizontal="true"
        android:layout_marginBottom="73dp"
        android:ems="10" >

        <requestFocus />
    </EditText>

</RelativeLayout>

1 个答案:

答案 0 :(得分:0)

我试过简要阅读代码。我不知道为什么会改变2个项目(也许是view.setAlpha行)。也许尝试使用位置变量,即

public void onItemClick(AdapterView<?> parent, View view,
     int position, long id) {
     // TODO Auto-generated method stub
     images[position].setAlpha((float)0.5);
}

正如我所说,我只是简单地阅读了代码。我希望这有帮助。