Gridview - 单击图像可在Viewpager中查看图像

时间:2012-11-22 10:41:00

标签: android json gridview android-viewpager universal-image-loader

这是一个从json获取图像的gridview。它工作正常。我想在此gridview中单击图像以显示完整图像并可以滑动它。我发现这个问题的解决方案是使用Viewpager。

如何在gridview中单击图像以显示图像并可以滑动?

您可以更轻松地阅读此代码。 http://pastebin.com/Q8Ljt9yL

enter image description here

public class MainActivity extends Activity {

public static final int DIALOG_DOWNLOAD_JSON_PROGRESS = 0;
private ProgressDialog mProgressDialog;
ArrayList<HashMap<String, Object>> MyArrList;

@SuppressLint("NewApi")
@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    // Permission StrictMode
    if (android.os.Build.VERSION.SDK_INT > 9) {
        StrictMode.ThreadPolicy policy = new StrictMode.ThreadPolicy.Builder().permitAll().build();
        StrictMode.setThreadPolicy(policy);
    }
    // Download JSON File
    new DownloadJSONFileAsync().execute();
} 

@Override
protected Dialog onCreateDialog(int id) {
    switch (id) {
    case DIALOG_DOWNLOAD_JSON_PROGRESS:
        mProgressDialog = new ProgressDialog(this);
        mProgressDialog.setMessage("Downloading.....");
        mProgressDialog.setProgressStyle(ProgressDialog.STYLE_SPINNER);
        mProgressDialog.setCancelable(true);
        mProgressDialog.show();
        return mProgressDialog;
    default:
        return null;
    }
}

public void ShowAllContent() {
    final GridView gridView1 = (GridView) findViewById(R.id.gridView1);
    gridView1.setAdapter(new ImageAdapter(MainActivity.this, MyArrList));
    gridView1.setOnItemClickListener(new OnItemClickListener() {

        @Override
        public void onItemClick(AdapterView<?> parent, View v, int position, long id) {

            Toast.makeText(getApplicationContext(), "this is", Toast.LENGTH_SHORT).show();
        }
    });
}

public class ImageAdapter extends BaseAdapter {
    private Context context;
    private ArrayList<HashMap<String, Object>> MyArr = new ArrayList<HashMap<String, Object>>();

    public ImageAdapter(Context c, ArrayList<HashMap<String, Object>> myArrList) {
        context = c;
        MyArr = myArrList;
    }

    public int getCount() {
        return MyArr.size();
    }

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

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

    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        View myView = convertView;
        viewHolder = new ViewHolder();
        if (convertView == null) {
            LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
            myView = inflater.inflate(R.layout.activity_column, null);

            viewHolder.imageView = (ImageView) myView.findViewById(R.id.ColImgPath);
            viewHolder.imageView.getLayoutParams().height = 120;
            viewHolder.imageView.getLayoutParams().width = 120;
            viewHolder.imageView.setPadding(5, 5, 5, 5);
            viewHolder.imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try {
                viewHolder.imageView.setImageBitmap((Bitmap) MyArr.get(position).get("ImageThumBitmap"));
            } catch (Exception e) {
                viewHolder.imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }
        }
        return myView;
    }
}

private static class ViewHolder {
    public ImageView imageView;
}

// Download JSON in Background
public class DownloadJSONFileAsync extends AsyncTask<String, Void, Void> {

    protected void onPreExecute() {
        super.onPreExecute();
        showDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }

    @Override
    protected Void doInBackground(String... params) {

        String url = "http://192.168.10.101/adchara1/";
        JSONArray data;
        try {
            data = new JSONArray(getJSONUrl(url));
            MyArrList = new ArrayList<HashMap<String, Object>>();
            HashMap<String, Object> map;

            for (int i = 0; i < data.length(); i++) {
                JSONObject c = data.getJSONObject(i);
                map = new HashMap<String, Object>();

                map.put("photo", (String) c.getString("photo"));
                map.put("ImageThumBitmap",(Bitmap) loadBitmap(c.getString("photo")));

                // Full (for View Popup)
                map.put("frame", (String) c.getString("frame"));

                MyArrList.add(map);
            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        return null;
    }

    protected void onPostExecute(Void unused) {
        ShowAllContent(); // When Finish Show Content
        dismissDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
        removeDialog(DIALOG_DOWNLOAD_JSON_PROGRESS);
    }
}

/*** Get JSON Code from URL ***/
public String getJSONUrl(String url) {
    StringBuilder str = new StringBuilder();
    HttpClient client = new DefaultHttpClient();
    HttpGet httpGet = new HttpGet(url);
    try {
        HttpResponse response = client.execute(httpGet);
        StatusLine statusLine = response.getStatusLine();
        int statusCode = statusLine.getStatusCode();
        if (statusCode == 200) { // Download OK
            HttpEntity entity = response.getEntity();
            InputStream content = entity.getContent();
            BufferedReader reader = new BufferedReader(new InputStreamReader(content));
            String line;
            while ((line = reader.readLine()) != null) {
                str.append(line);
            }
        } else {
            Log.e("Log", "Failed to download file..");
        }
    } catch (ClientProtocolException e) {
        e.printStackTrace();
    } catch (IOException e) {
        e.printStackTrace();
    }
    return str.toString();
}

/***** Get Image Resource from URL (Start) *****/
private static final String TAG = "Image";
private static final int IO_BUFFER_SIZE = 4 * 1024;

public static Bitmap loadBitmap(String url) {
    Bitmap bitmap = null;
    InputStream in = null;
    BufferedOutputStream out = null;

    try {
        in = new BufferedInputStream(new URL(url).openStream(),IO_BUFFER_SIZE);

        final ByteArrayOutputStream dataStream = new ByteArrayOutputStream();
        out = new BufferedOutputStream(dataStream, IO_BUFFER_SIZE);
        copy(in, out);
        out.flush();

        final byte[] data = dataStream.toByteArray();
        BitmapFactory.Options options = new BitmapFactory.Options();
        // options.inSampleSize = 1;

        bitmap = BitmapFactory.decodeByteArray(data, 0, data.length,options);
    } catch (IOException e) {
        Log.e(TAG, "Could not load Bitmap from: " + url);
    } finally {
        closeStream(in);
        closeStream(out);
    }
    return bitmap;
}

private static void closeStream(Closeable stream) {
    if (stream != null) {
        try {
            stream.close();
        } catch (IOException e) {
            android.util.Log.e(TAG, "Could not close stream", e);
        }
    }
}

private static void copy(InputStream in, OutputStream out)
        throws IOException {
    byte[] b = new byte[IO_BUFFER_SIZE];
    int read;
    while ((read = in.read(b)) != -1) {
        out.write(b, 0, read);
    }
}
}

4 个答案:

答案 0 :(得分:2)

首先,你必须实现ImageAdapter类&#39;方法getItem(int position)返回&#34;位置&#34;在MyArr。 接下来,在单击侦听器中,您可以执行类似

的操作
HashMap<String, Object> selected = (HashMap<String, Object>) gridView.getItemAtPosition(position);

选择后,您就拥有了位图。

答案 1 :(得分:2)

请参阅此class您可以找到

GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter());
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) {
                startImageGalleryActivity(position);
            }
        });

在这里,您将得到您想要的相同输出。

您还可以下载完整的源代码here

答案 2 :(得分:2)

和你需要的一样。只需单击网格视图的事件,然后使用视图寻呼机在下一个屏幕中获取图像。

单击网格视图图像的事件:

GridView gridView = (GridView) findViewById(R.id.gridview);
        gridView.setAdapter(new ImageAdapter());
        gridView.setOnItemClickListener(new OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view,
                    int position, long id) 
         {
          HashMap<String, Object> selected = (HashMap<String, Object>)  

          gridView.getItemAtPosition(position);

            }
        });

答案 3 :(得分:0)

是您图片的网址吗?

-> map.put("photo", (String) c.getString("photo"));//on your main activity

尝试在myView上使用onclick

myView.setOnClickListener(new OnClickListener() {
    @Override
    public void onClick(View v) {
        HashMap<String, Object> result = new HashMap<String, Object>();
        result = MyArr.get(position);
        Intent intent = new Intent(context, youractivitytarget.class);
        intent.putExtra("photo", (String)result.get(MainActivity.PHOTO));
        context.startActivity(intent);
    }
});

然后使用网址再次下载您点击的照片