如何将onClickListener添加到ListView

时间:2013-10-04 16:06:41

标签: android json android-listview onclicklistener

我有三个值,我使用JSON从mysql数据库中提取它们并在ListView中显示它们。我想要的是我想添加一个点击监听器。我有一个名为urlPageNumHolder的全局字符串变量来保存点击的ListView中的ID,因此当单击列表时,我希望调用loadPage()函数来显示ListVew中单击的项ID的Toast 。我试过了,但每当我点击列表中的项目时,它只会在ListView中最后一项的ID。请F1?以下是完整的代码。

  

MainActivity.java

package com.myapp;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.BufferedReader;
import java.io.ByteArrayOutputStream;
import java.io.Closeable;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;
import java.net.URL;
import java.util.ArrayList;
import java.util.HashMap;

import org.apache.http.HttpEntity;
import org.apache.http.HttpResponse;
import org.apache.http.StatusLine;
import org.apache.http.client.ClientProtocolException;
import org.apache.http.client.HttpClient;
import org.apache.http.client.methods.HttpGet;
import org.apache.http.impl.client.DefaultHttpClient;
import org.json.JSONArray;
import org.json.JSONException;
import org.json.JSONObject;

import android.app.Activity;
import android.app.ProgressDialog;
import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.os.AsyncTask;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;

public class MainActivity extends Activity {

    private ListView lstView;
    private ImageAdapter imageAdapter;

    public int currentPage = 1;
    public int TotalPage = 0;

    public Button btnNext;
    public Button btnPre;

    public String urlPageNumHolder;

    public ProgressDialog dialog;

    ArrayList<HashMap<String, Object>> MyArrList = new ArrayList<HashMap<String, Object>>();

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

        setContentView(R.layout.activity_main);

        // ListView and imageAdapter
        lstView = (ListView) findViewById(R.id.listView1);
        lstView.setClipToPadding(false);
        imageAdapter = new ImageAdapter(getApplicationContext());
        lstView.setAdapter(imageAdapter);

        // Next
        btnNext = (Button) findViewById(R.id.btnNext);
        // Perform action on click
        btnNext.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage + 1;
                ShowData();
            }
        });

        // Previous
        btnPre = (Button) findViewById(R.id.btnPre);
        // Perform action on click
        btnPre.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                currentPage = currentPage - 1;
                ShowData();
            }
        });

        // Show first load
        ShowData();

        // OnClick
            lstView.setOnItemClickListener(new OnItemClickListener() {
                public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
                    loadPage();
                }
            });

    }

    public void ShowData() {
        btnNext.setEnabled(false);
        btnPre.setEnabled(false);

        new LoadContentFromServer().execute();

        dialog = ProgressDialog.show(this, "News", "Loading...", true, false);
    }

    public void loadPage() {

            Toast.makeText(this, urlPageNumHolder, Toast.LENGTH_LONG).show();

    }


    class LoadContentFromServer extends AsyncTask<Object, Integer, Object> {

        @Override
        protected Object doInBackground(Object... params) {

            String url = "http://10.0.2.2/android/Pagination/getAllData.php";

            JSONArray data;
            try {
                data = new JSONArray(getJSONUrl(url));

                MyArrList = new ArrayList<HashMap<String, Object>>();
                HashMap<String, Object> map;

                int displayPerPage = 7; // Per Page
                int TotalRows = data.length();
                int indexRowStart = ((displayPerPage * currentPage) - displayPerPage);

                if (TotalRows <= displayPerPage) {
                    TotalPage = 1;
                } else if ((TotalRows % displayPerPage) == 0) {
                    TotalPage = (TotalRows / displayPerPage);
                } else {
                    TotalPage = (TotalRows / displayPerPage) + 1;
                    TotalPage = (int) TotalPage;
                }
                int indexRowEnd = displayPerPage * currentPage;
                if (indexRowEnd > TotalRows) {
                    indexRowEnd = TotalRows;
                }

                for (int i = indexRowStart; i < indexRowEnd; i++) {
                    JSONObject c = data.getJSONObject(i);
                    map = new HashMap<String, Object>();
                    map.put("ImageID", (String) c.getString("ImageID"));
                    map.put("ItemID", (String) c.getString("ItemID"));

                    // Thumbnail Get ImageBitmap To Object
                    map.put("ImagePath", (String) c.getString("ImagePath"));
                    Bitmap newBitmap = loadBitmap(c.getString("ImagePath"));
                    map.put("ImagePathBitmap", newBitmap);


                    MyArrList.add(map);

                    publishProgress(i);

                }

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

            return null;
        }

        @Override
        public void onProgressUpdate(Integer... progress) {
            imageAdapter.notifyDataSetChanged();
        }

        @Override
        protected void onPostExecute(Object result) {

            // Disabled Button Next
            if (currentPage >= TotalPage) {
                btnNext.setEnabled(false);
            } else {
                btnNext.setEnabled(true);
            }

            // Disabled Button Previos
            if (currentPage <= 1) {
                btnPre.setEnabled(false);
            } else {
                btnPre.setEnabled(true);
            }

            // dismiss the progress dialog
            if(dialog != null)  dialog.dismiss();
        }
    }

    class ImageAdapter extends BaseAdapter {

        private Context mContext;

        public ImageAdapter(Context context) {
            mContext = context;
        }

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

        public Object getItem(int position) {
            return MyArrList.get(position);
        }

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

        public View getView(int position, View convertView, ViewGroup parent) {
            // TODO Auto-generated method stub

            LayoutInflater inflater = (LayoutInflater) mContext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

            if (convertView == null) {
                convertView = inflater.inflate(R.layout.activity_column, null);
            }

            // ColImagePath
            ImageView imageView = (ImageView) convertView.findViewById(R.id.ColImagePath);
            imageView.getLayoutParams().height = 100;
            imageView.getLayoutParams().width = 100;
            imageView.setPadding(5, 5, 5, 5);
            imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
            try {
                imageView.setImageBitmap((Bitmap) MyArrList.get(position).get("ImagePathBitmap"));
            } catch (Exception e) {
                // When Error
                imageView.setImageResource(android.R.drawable.ic_menu_report_image);
            }

            // ColImageID
            TextView txtImgID = (TextView) convertView.findViewById(R.id.ColImageID);
            txtImgID.setPadding(10, 0, 0, 0);
            txtImgID.setText(MyArrList.get(position).get("ImageID").toString());


            // ColItemID
            TextView txtItemID = (TextView) convertView.findViewById(R.id.ColItemID);
            txtItemID.setPadding(10, 0, 0, 0);
            txtItemID.setText(MyArrList.get(position).get("ItemID").toString());


            //Hold Detail's URL
            urlPageNumHolder = MyArrList.get(position).get("ImageID").toString();


            return convertView;

        }

    }

    /*** 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);
        }
    }
    /***** Get Image Resource from URL (End) *****/

}

3 个答案:

答案 0 :(得分:0)

看起来你在点击时调用了loadPage,你需要传入点击了loadPage方法的索引,然后调用MyArrList.get(position);来获取你点击的位置,然后用它做你想做的任何事情

答案 1 :(得分:0)

urlPageNumHolder仅设置在一行urlPageNumHolder = MyArrList.get(position).get("ImageID").toString()中,与所点击的项目无关。

public void loadPage() {...}修改为

public void loadPage(long id) {
  Toast.makeText(this, String.valueOf(id), Toast.LENGTH_LONG).show();
}

并将其调用为:

listView.setOnItemClickListener(new OnItemClickListener() {
  public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
    loadPage(id);
  }
});

基本上,onItemClickListener会告诉您哪个项目被您最初忽略的id参数点击了。此参数应用于标识已单击的项目。

编辑: id可能不足以为您确定数据。在这种情况下,可以修改loadPage,如下所示。

public void loadPage(long id) {
  Toast.makeText(this, MyArrList.get(position).get("ImageID").toString(), Toast.LENGTH_LONG).show();
}

注意:我的代码可能无法正常工作,您可能需要执行一些int到long转换(反之亦然)

答案 2 :(得分:0)

我看到你发现onitemclicklistner很棒,但是按钮列表视图按钮消耗了点击。简单的解决方案是用textview或图标图标替换按钮。另一种解决方案是,你不能使用findviewbyid因为你必须在数组中的每个按钮上创建一个按钮数组和onitemclick侦听器。所以它将以编程方式完成而不是在xml中(无论如何都是按钮) 此外,我不确定您的列表适配器,因此YouTube幻灯片89 custombaseadapterhttp://m.youtube.com/watch?v = ka5Tk7J9rG0