如何在我的for循环linearlayout imageview中添加OnClickListener?

时间:2015-10-08 04:36:09

标签: java android android-fragments android-linearlayout

我需要帮助..

我有 HomeFragment.java

package com.example.administrator.mosbeau;


import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.Toast;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.load.resource.drawable.GlideDrawable;
import com.bumptech.glide.request.animation.GlideAnimation;
import com.bumptech.glide.request.target.GlideDrawableImageViewTarget;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;



/**
 * Created by Administrator on 9/7/2015.
 */

@SuppressWarnings("deprecation")

public class HomeFragment extends Fragment {

    public static HomeFragment newInstance() {
        HomeFragment fragment = new HomeFragment();
        return fragment;
    }

    public HomeFragment () {
    }

    Boolean InternetAvailable = false;
    Seocnd detectconnection;

    ImageView imageView, imageView3;
    ProgressBar progressBar, progressBar2, progressBar3;

    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS = "http://joehamirbalabadan.com/android/android/";

    String homeJSON, catid, catname;
    JSONArray jsonarray;
    LinearLayout layout;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        View rootView = inflater.inflate(R.layout.homelayout, container, false);

        detectconnection = new Seocnd(getActivity());
        InternetAvailable = detectconnection.InternetConnecting();
        if (InternetAvailable) {

            progressBar = (ProgressBar) rootView.findViewById(R.id.loading);
            progressBar.setVisibility(View.VISIBLE);
            imageView = (ImageView) rootView.findViewById(R.id.imageView);
            //Glide.with(getActivity()).load("http://joehamirbalabadan.com/android/android/imghome/index1.png").diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.indexloading).into(imageView);
            Glide.with(getActivity())
                    .load("http://joehamirbalabadan.com/android/android/imghome/index1.png").diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(new GlideDrawableImageViewTarget(imageView) {
                        @Override
                        public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                            super.onResourceReady(drawable, anim);
                            progressBar.setVisibility(View.GONE);
                        }
                    });

            progressBar2 = (ProgressBar) rootView.findViewById(R.id.loading2);
            progressBar2.setVisibility(View.VISIBLE);
            layout = (LinearLayout) rootView.findViewById(R.id.linear);
            getCategory();

            progressBar3 = (ProgressBar) rootView.findViewById(R.id.loading3);
            progressBar3.setVisibility(View.VISIBLE);
            imageView3 = (ImageView) rootView.findViewById(R.id.imageView3);
            //Glide.with(getActivity()).load("http://joehamirbalabadan.com/android/android/imghome/index3.png").diskCacheStrategy(DiskCacheStrategy.ALL).placeholder(R.drawable.indexloading).into(imageView3);
            Glide.with(getActivity())
                    .load("http://joehamirbalabadan.com/android/android/imghome/index3.png").diskCacheStrategy(DiskCacheStrategy.ALL)
                    .into(new GlideDrawableImageViewTarget(imageView3) {
                        @Override
                        public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                            super.onResourceReady(drawable, anim);
                            progressBar3.setVisibility(View.GONE);
                        }
                    });
        } else {
            NointernetFragment fragment = new NointernetFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();
        }

        return rootView;
    }

    public void getCategory() {
        class DownloadJSON extends AsyncTask<String, Void, String> {

            @Override
            protected String doInBackground(String... params) {
                HttpParams httpRequestParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost(SERVER_ADDRESS + "categories.php");

                // Depends on your web service
                //httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null) {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                } finally {
                    try {
                        if (inputStream != null) inputStream.close();
                    } catch (Exception squish) {
                    }
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result) {
                homeJSON = result;

                try {
                    // Locate the array name in JSON
                    JSONObject jsonObj = new JSONObject(result);
                    jsonarray = jsonObj.getJSONArray("result");

                    for (int i = 0; i < jsonarray.length(); i++) {
                        JSONObject p = jsonarray.getJSONObject(i);
                        ImageView thumbView = new ImageView(getActivity());
                        catid = p.getString("categories_id");
                        catname = p.getString("categories_name");
                        thumbView.setId(i);
                        thumbView.setPadding(0, 0, 10, 0);
                        /*Glide.with(getActivity()).load(p.getString("categories_image")).override(336, 269).diskCacheStrategy(DiskCacheStrategy.ALL).into(thumbView);*/
                        Glide.with(getActivity())
                                .load(p.getString("categories_image")).diskCacheStrategy(DiskCacheStrategy.ALL)
                                .override(336, 269)
                                .into(new GlideDrawableImageViewTarget(thumbView) {
                                    @Override
                                    public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                                        super.onResourceReady(drawable, anim);
                                        progressBar2.setVisibility(View.GONE);
                                    }
                                });
                        layout.addView(thumbView);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }
            }
        }
        DownloadJSON g = new DownloadJSON();
        g.execute();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(1);
    }

}

我想将OnClickListener添加到此代码中。

for (int i = 0; i < jsonarray.length(); i++) {
    JSONObject p = jsonarray.getJSONObject(i);
    ImageView thumbView = new ImageView(getActivity());
    catid = p.getString("categories_id");
    catname = p.getString("categories_name");
    thumbView.setId(i);
    thumbView.setPadding(0, 0, 10, 0);

    Glide.with(getActivity())
            .load(p.getString("categories_image")).diskCacheStrategy(DiskCacheStrategy.ALL)
            .override(336, 269)
            .into(new GlideDrawableImageViewTarget(thumbView) {
                @Override
                public void onResourceReady(GlideDrawable drawable, GlideAnimation anim) {
                    super.onResourceReady(drawable, anim);
                    progressBar2.setVisibility(View.GONE);
                }
            });
    layout.addView(thumbView);
}

点击图片后,我想将 HomeFragment.java 更改为 CategoryFragment.java 并传递 catid catname 到我的CategoryFragment.java

这是我的 CategoryFragment.java

package com.example.administrator.mosbeau;

import android.app.Activity;
import android.app.Fragment;
import android.app.FragmentManager;
import android.app.ProgressDialog;
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.GridView;
import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.NameValuePair;
import org.apache.http.client.entity.UrlEncodedFormEntity;
import org.apache.http.client.methods.HttpPost;
import org.apache.http.impl.client.DefaultHttpClient;
import org.apache.http.message.BasicNameValuePair;
import org.apache.http.params.BasicHttpParams;
import org.apache.http.params.HttpConnectionParams;
import org.apache.http.params.HttpParams;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;
import java.io.BufferedReader;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.util.ArrayList;
import java.util.HashMap;

/**
 * Created by Administrator on 9/18/2015.
 */

@SuppressWarnings("deprecation")

public class CategoryFragment extends Fragment {

    public static CategoryFragment newInstance(String id,String name) {
        CategoryFragment fragment = new CategoryFragment();

        Bundle bundle = new Bundle();
        bundle.putString("id", id);
        bundle.putString("name", name);
        fragment.setArguments(bundle);

        return fragment;
    }

    public CategoryFragment () {
    }

    String cid;
    String cname;

    public static final int CONNECTION_TIMEOUT = 1000 * 15;
    public static final String SERVER_ADDRESS = "http://joehamirbalabadan.com/android/android/";

    String myJSON;
    JSONArray jsonarray;
    GridView productgridview;
    GridViewAdapter adapter;
    ProgressDialog mProgressDialog;
    ArrayList<HashMap<String, String>> arraylist;
    public static String products_id = "products_id";
    public static String products_name = "products_name";
    public static String products_price = "products_price";
    public static String products_image = "products_image";

    Boolean InternetAvailable = false;
    Seocnd detectconnection;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
        View rootView = inflater.inflate(R.layout.categorylayout, container, false);

        getActivity().invalidateOptionsMenu();

        if(getArguments() != null) {
            String catid = getArguments().getString("id");
            String catname = getArguments().getString("name");

            cid = catid;
            cname = catname;
        }

        productgridview = (GridView) rootView.findViewById(R.id.productgridview);

        //new DownloadJSON().execute();

        detectconnection = new Seocnd(getActivity());
        InternetAvailable = detectconnection.InternetConnecting();
        if (InternetAvailable) {
            getProduct();
        } else {
            NointernetFragment fragment = new NointernetFragment();
            FragmentManager fragmentManager = getFragmentManager();
            fragmentManager.beginTransaction()
                    .replace(R.id.container, fragment)
                    .commit();
        }

        return rootView;
    }

    public void getProduct(){
        class DownloadJSON extends AsyncTask<String, Void, String> {

            @Override
            protected void onPreExecute() {
                super.onPreExecute();
                // Create a progressdialog
                mProgressDialog = new ProgressDialog(getActivity());
                // Set progressdialog title
                mProgressDialog.setTitle(cname);
                // Set progressdialog message
                mProgressDialog.setMessage("Loading...");
                mProgressDialog.setIndeterminate(false);
                // Show progressdialog
                mProgressDialog.show();
            }

            @Override
            protected String doInBackground(String... params) {
                ArrayList<NameValuePair> dataToSend = new ArrayList<>();
                dataToSend.add(new BasicNameValuePair("cid", cid));
                dataToSend.add(new BasicNameValuePair("cname", cname));

                HttpParams httpRequestParams = new BasicHttpParams();
                HttpConnectionParams.setConnectionTimeout(httpRequestParams, CONNECTION_TIMEOUT);
                HttpConnectionParams.setSoTimeout(httpRequestParams, CONNECTION_TIMEOUT);

                DefaultHttpClient httpclient = new DefaultHttpClient(new BasicHttpParams());
                HttpPost httppost = new HttpPost(SERVER_ADDRESS + "products.php");

                // Depends on your web service
                //httppost.setHeader("Content-type", "application/json");

                InputStream inputStream = null;
                String result = null;
                try {
                    httppost.setEntity(new UrlEncodedFormEntity(dataToSend));
                    HttpResponse response = httpclient.execute(httppost);
                    HttpEntity entity = response.getEntity();

                    inputStream = entity.getContent();
                    // json is UTF-8 by default
                    BufferedReader reader = new BufferedReader(new InputStreamReader(inputStream, "UTF-8"), 8);
                    StringBuilder sb = new StringBuilder();

                    String line = null;
                    while ((line = reader.readLine()) != null)
                    {
                        sb.append(line + "\n");
                    }
                    result = sb.toString();
                } catch (Exception e) {
                    // Oops
                }
                finally {
                    try{if(inputStream != null)inputStream.close();}catch(Exception squish){}
                }
                return result;
            }

            @Override
            protected void onPostExecute(String result){
                myJSON=result;

                try {
                    // Locate the array name in JSON
                    JSONObject jsonObj = new JSONObject(myJSON);
                    jsonarray = jsonObj.getJSONArray("products");

                    arraylist = new ArrayList<HashMap<String, String>>();

                    for (int i = 0; i < jsonarray.length(); i++) {
                        HashMap<String, String> map = new HashMap<String, String>();
                        JSONObject p = jsonarray.getJSONObject(i);
                        // Retrive JSON Objects
                        map.put("products_id", p.getString("products_id"));
                        map.put("products_name", p.getString("products_name"));
                        map.put("products_price", p.getString("products_price"));
                        map.put("products_image", p.getString("products_image"));
                        // Set the JSON Objects into the array
                        arraylist.add(map);
                    }
                } catch (JSONException e) {
                    Log.e("Error", e.getMessage());
                    e.printStackTrace();
                }

                adapter = new GridViewAdapter(getActivity(), arraylist);
                // Set the adapter to the GridView
                productgridview.setAdapter(adapter);
                // Close the progressdialog
                mProgressDialog.dismiss();
            }
        }
        DownloadJSON g = new DownloadJSON();
        g.execute();
    }

    @Override
    public void onAttach(Activity activity) {
        super.onAttach(activity);
        ((MainActivity) activity).onSectionAttached(2);
    }
}

1 个答案:

答案 0 :(得分:1)

您可以使用“标记”功能。

for (int i = 0; i < jsonarray.length(); i++) {
  JSONObject p = jsonarray.getJSONObject(i);
  ImageView thumbView = new ImageView(getActivity());
  catid = p.getString("categories_id");
  catname = p.getString("categories_name");

  //Here you can use HashMap, Custom Object also
  String catDetailsString = catid + "," + catname;
  tumbView.setTag(catDetailsString);

  thumbView.setOnClickListener(new View.OnClickListener() { 
     public void onClick(View view) { 
           String catDetails = (String) view.getTag();
           String[] catDetailsArray = catDetails.split(",");
           String categoryId = catDetailsArray[0];
           String categoryName = catDetailsArray[1];

          //Passinng Category Id and name to CategoryFragment
          CategoryFragment categoryFragment = CategoryFragment.newInstance(categoryId, categoryName);
          FragmentManager fragmentManager = getFragmentManager();
        fragmentManager.beginTransaction()
                .replace(R.id.container, categoryFragment)
                .commit();

      }
   });
  //Your code goes here
 }