Gridview - 单击gridview项以在imageview中显示图像

时间:2012-10-18 01:23:50

标签: android json gridview imageview onitemclicklistener

我按照这个动作Android Lazy Loading images and text in listview from http json data,现在我将listview更改为gridview。

我的问题是

我想点击gridview项目并在imageview中显示图片

MainActivity

public class MainActivity extends Activity {

GridView gridView;

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

    String strUrl = "http://ta.wptrafficanalyzer.in/demo1/first.php/countries/";
    DownloadTask downloadTask = new DownloadTask();
    downloadTask.execute(strUrl);

    gridView = (GridView) findViewById(R.id.lv_countries);
    gridView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v, int positon,
                long id) {
            Toast.makeText(getApplicationContext(), "welcome to hello gridview", Toast.LENGTH_SHORT).show();
        }
    });

}

private String downloadUrl(String strUrl) throws IOException{
    String data = "";
    InputStream iStream = null;
    try{
        URL url = new URL(strUrl);
        HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
        urlConnection.connect();
        iStream = urlConnection.getInputStream();
        BufferedReader br = new BufferedReader(new InputStreamReader(iStream));
        StringBuffer sb  = new StringBuffer();
        String line = "";
        while( ( line = br.readLine())  != null){
            sb.append(line);
        }

        data = sb.toString();
        br.close();

    }catch(Exception e){
        Log.d("Exception while downloading url", e.toString());
    }finally{
        iStream.close();
    }

    return data;
}

private class DownloadTask extends AsyncTask<String, Integer, String>{
    String data = null;
    @Override
    protected String doInBackground(String... url) {
        try{
            data = downloadUrl(url[0]);
        }catch(Exception e){
            Log.d("Background Task",e.toString());
        }
        return data;
    }

    @Override
    protected void onPostExecute(String result) {
        ListViewLoaderTask listViewLoaderTask = new ListViewLoaderTask();
        listViewLoaderTask.execute(result);
    }
}

private class ListViewLoaderTask extends AsyncTask<String, Void, SimpleAdapter>{

    JSONObject jObject;
    @Override
    protected SimpleAdapter doInBackground(String... strJson) {
        try{
            jObject = new JSONObject(strJson[0]);
            CountryJSONParser countryJsonParser = new CountryJSONParser();
            countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("JSON Exception1",e.toString());
        }

        CountryJSONParser countryJsonParser = new CountryJSONParser();
        List<HashMap<String, Object>> countries = null;

        try{
            countries = countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }

        String[] from = { "country","flag","details"};
        int[] to = { R.id.tv_country,R.id.iv_flag,R.id.tv_country_details};
        SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.lv_layout, from, to);

        return adapter;
    }

    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        gridView.setAdapter(adapter);

        for(int i=0;i<adapter.getCount();i++){
            HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(i);
            String imgUrl = (String) hm.get("flag_path");
            ImageLoaderTask imageLoaderTask = new ImageLoaderTask();

            HashMap<String, Object> hmDownload = new HashMap<String, Object>();
            hm.put("flag_path",imgUrl);
            hm.put("position", i);

            imageLoaderTask.execute(hm);
        }
    }
}

private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

    @Override
    protected HashMap<String, Object> doInBackground(HashMap<String, Object>... hm) {

        InputStream iStream=null;
        String imgUrl;
        imgUrl = (String) hm[0].get("flag_path");
        int position = (Integer) hm[0].get("position");

        URL url;
        try {
            url = new URL(imgUrl);
            HttpURLConnection urlConnection = (HttpURLConnection) url.openConnection();
            urlConnection.connect();
            iStream = urlConnection.getInputStream();

            File cacheDirectory = getBaseContext().getCacheDir();
            File tmpFile = new File(cacheDirectory.getPath() + "/wpta_"+position+".png");
            FileOutputStream fOutStream = new FileOutputStream(tmpFile);

            Bitmap b = BitmapFactory.decodeStream(iStream);
            b.compress(Bitmap.CompressFormat.PNG,100, fOutStream);

            fOutStream.flush();
            fOutStream.close();
            HashMap<String, Object> hmBitmap = new HashMap<String, Object>();

            hmBitmap.put("flag",tmpFile.getPath());
            hmBitmap.put("position",position);

            return hmBitmap;

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

    @Override
    protected void onPostExecute(HashMap<String, Object> result) {
        String path = (String) result.get("flag");
        int position = (Integer) result.get("position");

        SimpleAdapter adapter = (SimpleAdapter ) gridView.getAdapter();
        HashMap<String, Object> hm = (HashMap<String, Object>) adapter.getItem(position);
        hm.put("flag",path);

        adapter.notifyDataSetChanged();
    }
}

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.activity_main, menu);
    return true;
}

} CountryJSONParser.java

public class CountryJSONParser {

public List<HashMap<String,Object>> parse(JSONObject jObject){

    JSONArray jCountries = null;
    try {
        jCountries = jObject.getJSONArray("countries");
    } catch (JSONException e) {
        e.printStackTrace();
    }

    return getCountries(jCountries);
}

private List<HashMap<String, Object>> getCountries(JSONArray jCountries){
    int countryCount = jCountries.length();
    List<HashMap<String, Object>> countryList = new ArrayList<HashMap<String,Object>>();
    HashMap<String, Object> country = null;

    for(int i=0; i<countryCount;i++){
        try {
            country = getCountry((JSONObject)jCountries.get(i));
            countryList.add(country);

        } catch (JSONException e) {
            e.printStackTrace();
        }
    }

    return countryList;
}

private HashMap<String, Object> getCountry(JSONObject jCountry){

    HashMap<String, Object> country = new HashMap<String, Object>();
    String countryName = "";
    String flag="";
    String language = "";
    String capital = "";
    String currencyCode = "";
    String currencyName = "";

    try {
        countryName = jCountry.getString("countryname");
        flag = jCountry.getString("flag");
        language = jCountry.getString("language");
        capital = jCountry.getString("capital");
        currencyCode = jCountry.getJSONObject("currency").getString("code");
        currencyName = jCountry.getJSONObject("currency").getString("currencyname");

        String details =        "Language : " + language + "\n" +
                            "Capital : " + capital + "\n" +
                            "Currency : " + currencyName + "(" + currencyCode + ")";

        country.put("country", countryName);
        country.put("flag", R.drawable.blank);
        country.put("flag_path", flag);
        country.put("details", details);

    } catch (JSONException e) {
        e.printStackTrace();
    }
    return country;
}

}

当完成但gridview显示图像不正确时

<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" >

activity_man.xml

<GridView
    android:id="@+id/lv_countries"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent"
    android:columnWidth="90dp"
    android:numColumns="auto_fit"
    android:verticalSpacing="10dp"
    android:horizontalSpacing="10dp"
    android:stretchMode="columnWidth"
    android:gravity="center"
    tools:context=".MainActivity" />

ly_layout.xml

<?xml version="1.0" encoding="utf-8"?>

<ImageView
    android:id="@+id/iv_flag"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:contentDescription="@string/str_iv_flag" />

enter image description here

1 个答案:

答案 0 :(得分:2)

在gridview onClickListener中获取点击项目的数据

gridView.setOnItemClickListener(new OnItemClickListener() {

        public void onItemClick(AdapterView<?> parent, View v, int positon,
                long id) {
HashMap<String, Object> hm = gridView.getAdapter().getPosition(positon);

   String imgPath = (String) hm.get("flag"); //get downloaded image path
Intent i = new Intent(yourActivityContext, NewActivityToDisplayImage.class); //start new Intent to another Activity.
i.putExtra("ClickedImagePath", imgPath ); //put image link in intent.
startActivity(i);

        }
    });

NewActivityToDisplayImage获取图片路径并设置为imageview。

public class NewActivityToDisplayImage extends Activity {

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

        String imagePath = getIntent().getStringExtra("ClickedImagePath"); //get image path from post activity
        if (imagePath != null && !imagePath.isEmpty) {
            File imgFile = new File(imagePath);
            if (imgFile.exists()) {

                Bitmap myBitmap = BitmapFactory.decodeFile(imgFile.getAbsolutePath());

                ImageView myImage = (ImageView) findViewById(R.id.imageviewTest);
                myImage.setImageBitmap(myBitmap);

            }

        }

    }}
相关问题