将for循环中的值传递给android中的方法

时间:2015-12-29 10:53:20

标签: android function for-loop onclicklistener

我正在尝试将listview索引的位置传递给一个用户定义函数。该功能适用​​于listview中按钮的点击事件。 这是我的代码:    公共课蔬菜扩展活动{

ProgressDialog pDialog;
ListView mListView;
SimpleAdapter adapter;
private Activity activity;  
AQuery aq;
public int idx;

private JSONArray mComments = null;

private ArrayList<HashMap<String, Object>> mCommentList;

ArrayList<HashMap<String, Object>> searchResults;
public Activity context;

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);    
    setContentView(R.layout.vegetables);   
    aq=new AQuery(this);

    String strUrl = "http://gaubharat.in/gaubharat/first.php";

    DownloadTask downloadTask = new DownloadTask();


    downloadTask.execute(strUrl);


    mListView = (ListView) findViewById(R.id.lv_vegetable);       
}



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>{
    /*LayoutInflater inflater = context.getLayoutInflater();
    View rowView = inflater.inflate(R.layout.vegetables, null, true);*/

    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());
        }       

        // Instantiating json parser class
        CountryJSONParser countryJsonParser = new CountryJSONParser();

        // A list object to store the parsed countries list
        List<HashMap<String, Object>> countries = null;

        try{
            // Getting the parsed data as a List construct
            countries = countryJsonParser.parse(jObject);
        }catch(Exception e){
            Log.d("Exception",e.toString());
        }          

        String[] from = {"product_name","product_memberprice","product_minquantity","product_image"};

        // Ids of views in listview_layout
        int[] to = { R.id.product_name,R.id.unitprice,R.id.minqty,R.id.img};

        // Instantiating an adapter to store each items
        // R.layout.listview_layout defines the layout of each item         
    SimpleAdapter adapter = new SimpleAdapter(getBaseContext(), countries, R.layout.productlayout, from, to);  
    return adapter;

    }


    /** Invoked by the Android on "doInBackground" is executed */
    @Override
    protected void onPostExecute(SimpleAdapter adapter) {

        // Setting adapter for the listview
        mListView.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);

            // Starting ImageLoaderTask to download and populate image in the listview 
            imageLoaderTask.execute(hm); 


            //addtocart(mListView,i);

             idx = i;

        }

    }       
}

public void addtocart(View v){

    //final int index = i;
     mListView = (ListView) findViewById(R.id.lv_vegetable);

    LinearLayout vwParentRow = (LinearLayout)v.getParent();

    TextView child = (TextView)vwParentRow.getChildAt(0);
    ImageView img = (ImageView)vwParentRow.getChildAt(1);
    TextView qty = (TextView)vwParentRow.getChildAt(2);
    TextView pr = (TextView)vwParentRow.getChildAt(3);
    Button btnChild = (Button)vwParentRow.getChildAt(4);


    btnChild.setOnClickListener(new OnClickListener() {

        @Override
        public void onClick(View v) {

    Toast.makeText(Vegetables.this,"Index" + idx ,Toast.LENGTH_LONG ).show();
        }
    });

    vwParentRow.refreshDrawableState();
}

/** AsyncTask to download and load an image in ListView */
 private class ImageLoaderTask extends AsyncTask<HashMap<String, Object>, Void, HashMap<String, Object>>{

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

        InputStream iStream=null;

        String 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("product_image",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("product_image");           

        int position = (Integer) result.get("position");

        SimpleAdapter adapter = (SimpleAdapter ) mListView.getAdapter();

        HashMap<String, Object> hm = (HashMap<String, Object>)adapter.getItem(position);    

        hm.put("product_image",path);

        adapter.notifyDataSetChanged(); 
    }
}

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;

   }

    return super.onOptionsItemSelected(item);
}      
}

我在按钮点击时收到idx值,但这是for循环的最后一个值。 请帮助我。

1 个答案:

答案 0 :(得分:1)

这里的代码public partial class formA : Form { public formA() { InitializeComponent(); } private void button1_Click(object sender, EventArgs e) { formB b = new formB(); b.owner = this; b.ShowDialog(); } } 由i在每次循环迭代中设置,因此您只获得最后一个值。 For循环不会等你。

您需要在idx上使用OnItemClickListener

ListView