列表视图中的按钮事件[英] Button events in listview

本文是小编为大家收集整理的关于列表视图中的按钮事件的处理/解决方法,可以参考本文帮助大家快速定位并解决问题,中文翻译不准确的可切换到English标签页查看源文。

问题描述

我有 listView,我在其中膨胀一行包含 textview 和按钮,现在我想处理在适配器中编码的按钮的点击事件,我也能够获得按钮的位置.但是在这里,当我单击按钮时,我正在更改按钮的图像,它的工作正常问题 是当我滚动视图时,它再次更改按钮的图像,因为 getview() 方法对其进行了回收每次都查看.

如何在适配器中处理上述功能?

下面是在adpater中编码的按钮事件代码.

holder.download.setTag(position) ;

        holder.download.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                pos =(Integer) v.getTag() ; 
                Log.d("*******************************", ""+pos);
                Constant.buttonStates[pos]=1;   
        pref = activity.getSharedPreferences("status", MODE_PRIVATE);
                SharedPreferences.Editor edit=pref.edit();
                edit.putInt("s",Constant.buttonStates[pos]);
                //edit.putString("s",  Constant.buttonStates.toString());
                edit.commit();

                check[pos]=pref.getInt("s", 1);

                v.setBackgroundResource(R.drawable.right);
                try {
                    new PubDetailsTask().execute("");
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });

下面是我处理按钮事件的适配器.

public class PublicationAdapter extends BaseAdapter implements
    DownloadThreadListener {

    private LayoutInflater mInflater;
    private SQLiteDBAssistant sqlliteCity;
    private DownloadThread downloadThread;
    private Handler handler;
    public ImageLoader imageLoader;
    static String videoUrl, downloadImage, downloadVideo, name, url,
        output = "", selId = "";
    int pos, btnpos, tempos;
    JSONArray globalData, arrListFinal;
    Activity activity;
    Bitmap bbicon;
    ArrayList<String> imageUrl = new ArrayList<String>();
    AlertDialog.Builder downloadDialog;
    AlertDialog downloadMsg;
    ViewHolder holder;
    String author[];
    HttpManager httpObject;
        String pub_id = "", title = "", avgrat = "", content = "", authorname = "",
        mediafile = "", docurl = "", thumburl = "", peerrat = "",
        profrat = "", comrat = "", peerrank = "", profrank = "",
        comrank = "", urid = "", uravgrat = "", urrole = "",
        imagePath = "";
    String video_SDpath = "";
    int[] buttonStates;

    public PublicationAdapter(Activity a, JSONArray arrList) {

               httpObject = new HttpManager();
       globalData = arrList;
       activity = a;

       mInflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       imageLoader = new ImageLoader(activity.getApplicationContext());
       Constant.publicationIdArraylist = new ArrayList<String>();
       downloadThread = new DownloadThread(PublicationAdapter.this, activity);
       downloadThread.start();
       handler = new Handler();

       buttonStates = new int[globalData.length()];
       for (int i = 0; i < globalData.length(); i++) {
            buttonStates[i] = 0;
       }

       downloadDialog = new AlertDialog.Builder(a);
       downloadDialog.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    downloadMsg.dismiss();
                }
       });
       downloadMsg = downloadDialog.create();

   }
   public int getCount() {
    return globalData.length();
   }
   public Object getItem(int postionitem) {
    return postionitem;
   }
   public long getItemId(int positionitemId) {
    return positionitemId;
   }
   public void setSelectedPosition(int pos) {
    tempos = pos;
    // inform the view of this change
    notifyDataSetChanged();
       }
   public int getSelectedPosition() {
    return tempos;
   }
   public class ViewHolder {
    TextView twtdata;
    ImageView twtimg;
    TextView twtnm;
    Bitmap image;
    Button download;
   }

   public View getView(final int position, View convertView, ViewGroup parent) {

          View vi = convertView;
          if (convertView == null) {

               vi = mInflater.inflate(R.layout.listrowplaylists, null);

               holder = new ViewHolder();
               holder.twtdata = (TextView) vi.findViewById(R.id.txtauthor);
               holder.twtnm = (TextView) vi.findViewById(R.id.txtlisttitle);
               holder.twtimg = (ImageView) vi.findViewById(R.id.avatar);
               holder.download = (Button) vi.findViewById(R.id.btn_download);

               if (buttonStates[position] == 0)
                 holder.download.setBackgroundResource(R.drawable.downloadicon); //button not clicked   
                           else 
                holder.download.setBackgroundResource(R.drawable.right); // button clicked
               vi.setTag(holder);
        }
        else 
        {
              holder = (ViewHolder) vi.getTag();
        }

        try {

              JSONObject firstObject = globalData.optJSONObject(position);
              Log.i("Publication", firstObject.toString());

              holder.twtnm.setText(firstObject.getString("Title"));
              imageUrl.add(firstObject.optString("ThumbnailUrl"));
              holder.twtimg.setTag(imageUrl.get(position));
              imageLoader.DisplayImage(imageUrl.get(position), activity,
                holder.twtimg);

              Constant.publicationIdArraylist.add(firstObject.getString("Id"));
              Log.i("ID IN LIST", "=================="
                + Constant.publicationIdArraylist.get(position));

             JSONArray firstarray = firstObject.getJSONArray("Authors");
             int len = firstarray.length();
             author = new String[len];

             for (int j = 0; j < firstarray.length(); j++) {
                JSONObject third = firstarray.getJSONObject(j);
                author[j] = authorname = third.getString("AuthorName");
             }
             try {
                holder.twtdata.setText(author[0] + ", " + author[1]);
             } 
             catch (Exception e) {              
             }
       } 
       catch (Exception e) {
               e.printStackTrace();
       }
       holder.download.setTag(position);

       holder.download.setOnClickListener(new OnClickListener() {

              public void onClick(View v) {

                 pos = (Integer) v.getTag();
                 Log.d("*******************************", "" + pos);
                 buttonStates[pos] = 1;
                 v.setBackgroundResource(R.drawable.right);
                 selId = Constant.publicationIdArraylist.get(position);
                 System.out.println("buton clicked id  " + selId);
                 try {
                     new PubDetailsTask().execute("");
                 }
                                 catch (Exception e) {
                 }
             }
       });
       return vi;
}

谢谢.

推荐答案

假设你有 CustomAdapter.class 来填充你的列表视图,然后:

public class CustomAdapter extends ArrayAdapter<String> {

        String[] array;
    Context mContext;
    LayoutInflater mInflater;
    int[] buttonStates;

    public CustomAdapter(Context context, int textViewResourceId,
            String[] objects)
    {
        super(context, textViewResourceId, objects);
        array=objects;
        mContext=context;
        mInflater = LayoutInflater.from(context);
        //save all buttons state as 0(not clicked) initially
        buttonStates=new int[objects.length];
            for(int i=0;i<objects.length;i++)
            { 
                   buttonStates[i]=0;
            }  
    }  
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ...
         if(buttonStates[position]==0)
         {
             holder.button.setBackgroundResource(R.drawable.bg_normal);  //set background for button "not clicked"          
         }
         else
         {
             holder.button.setBackgroundResource(R.drawable.bg_pressed);  //set background for button "clicked"                 
         }

         final int pos=position;
         holder.download.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                buttonStates[pos]=1;                
                holder.button.setBackgroundResource(R.drawable.bg_clicked);                
            }
        });         
    }  
}

我已经测试了这个,它对我来说很好用!

编辑:

您需要添加以下代码行:

if (buttonStates[position] == 0)
         holder.download.setBackgroundResource(R.drawable.downloadicon); // set background for button "not clicked"             
else
         holder.download.setBackgroundResource(R.drawable.right); // set background for button "clicked"

外侧if(convertView == null)...else....所以把代码放在你写之前:

holder.download.setOnClickListener(new OnClickListener() {
...}

这将解决您的问题.

当你把它放入 if(convertView==null) 时,它只会调用一次.所以你得到了你在评论中向我描述的问题!

其他推荐答案

在 getView 中,我们总是重新创建视图,所以你怎么能期望一个按钮即使在再次调用 getView 之后也会存储其先前的状态.因此,将每个按钮的状态存储在一个数组中,并根据 getView() 本身内部的这个数组设置背景颜色.

本文地址:https://www.itbaoku.cn/post/102369.html

问题描述

I have listView in which I inflate a row contain textview and button now I want to handle click event of button which coded in adapter and I am able to get the position of button too. But here when I click on button I am changing a image of button its works fine problem is when I scroll the view it again change the image of button as it was before because of getview() Method its recycle view every time.

How to handle above functionality in adapter?

Below is the button event code which is coded in adpater.

holder.download.setTag(position) ;

        holder.download.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {
                pos =(Integer) v.getTag() ; 
                Log.d("*******************************", ""+pos);
                Constant.buttonStates[pos]=1;   
        pref = activity.getSharedPreferences("status", MODE_PRIVATE);
                SharedPreferences.Editor edit=pref.edit();
                edit.putInt("s",Constant.buttonStates[pos]);
                //edit.putString("s",  Constant.buttonStates.toString());
                edit.commit();

                check[pos]=pref.getInt("s", 1);

                v.setBackgroundResource(R.drawable.right);
                try {
                    new PubDetailsTask().execute("");
                } catch (Exception e) {
                    // TODO: handle exception
                }
            }
        });

Below is the adapter in which I am handling a button events.

public class PublicationAdapter extends BaseAdapter implements
    DownloadThreadListener {

    private LayoutInflater mInflater;
    private SQLiteDBAssistant sqlliteCity;
    private DownloadThread downloadThread;
    private Handler handler;
    public ImageLoader imageLoader;
    static String videoUrl, downloadImage, downloadVideo, name, url,
        output = "", selId = "";
    int pos, btnpos, tempos;
    JSONArray globalData, arrListFinal;
    Activity activity;
    Bitmap bbicon;
    ArrayList<String> imageUrl = new ArrayList<String>();
    AlertDialog.Builder downloadDialog;
    AlertDialog downloadMsg;
    ViewHolder holder;
    String author[];
    HttpManager httpObject;
        String pub_id = "", title = "", avgrat = "", content = "", authorname = "",
        mediafile = "", docurl = "", thumburl = "", peerrat = "",
        profrat = "", comrat = "", peerrank = "", profrank = "",
        comrank = "", urid = "", uravgrat = "", urrole = "",
        imagePath = "";
    String video_SDpath = "";
    int[] buttonStates;

    public PublicationAdapter(Activity a, JSONArray arrList) {

               httpObject = new HttpManager();
       globalData = arrList;
       activity = a;

       mInflater = (LayoutInflater) activity
            .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
       imageLoader = new ImageLoader(activity.getApplicationContext());
       Constant.publicationIdArraylist = new ArrayList<String>();
       downloadThread = new DownloadThread(PublicationAdapter.this, activity);
       downloadThread.start();
       handler = new Handler();

       buttonStates = new int[globalData.length()];
       for (int i = 0; i < globalData.length(); i++) {
            buttonStates[i] = 0;
       }

       downloadDialog = new AlertDialog.Builder(a);
       downloadDialog.setPositiveButton("OK",
            new DialogInterface.OnClickListener() {

                public void onClick(DialogInterface dialog, int which) {
                    downloadMsg.dismiss();
                }
       });
       downloadMsg = downloadDialog.create();

   }
   public int getCount() {
    return globalData.length();
   }
   public Object getItem(int postionitem) {
    return postionitem;
   }
   public long getItemId(int positionitemId) {
    return positionitemId;
   }
   public void setSelectedPosition(int pos) {
    tempos = pos;
    // inform the view of this change
    notifyDataSetChanged();
       }
   public int getSelectedPosition() {
    return tempos;
   }
   public class ViewHolder {
    TextView twtdata;
    ImageView twtimg;
    TextView twtnm;
    Bitmap image;
    Button download;
   }

   public View getView(final int position, View convertView, ViewGroup parent) {

          View vi = convertView;
          if (convertView == null) {

               vi = mInflater.inflate(R.layout.listrowplaylists, null);

               holder = new ViewHolder();
               holder.twtdata = (TextView) vi.findViewById(R.id.txtauthor);
               holder.twtnm = (TextView) vi.findViewById(R.id.txtlisttitle);
               holder.twtimg = (ImageView) vi.findViewById(R.id.avatar);
               holder.download = (Button) vi.findViewById(R.id.btn_download);

               if (buttonStates[position] == 0)
                 holder.download.setBackgroundResource(R.drawable.downloadicon); //button not clicked   
                           else 
                holder.download.setBackgroundResource(R.drawable.right); // button clicked
               vi.setTag(holder);
        }
        else 
        {
              holder = (ViewHolder) vi.getTag();
        }

        try {

              JSONObject firstObject = globalData.optJSONObject(position);
              Log.i("Publication", firstObject.toString());

              holder.twtnm.setText(firstObject.getString("Title"));
              imageUrl.add(firstObject.optString("ThumbnailUrl"));
              holder.twtimg.setTag(imageUrl.get(position));
              imageLoader.DisplayImage(imageUrl.get(position), activity,
                holder.twtimg);

              Constant.publicationIdArraylist.add(firstObject.getString("Id"));
              Log.i("ID IN LIST", "=================="
                + Constant.publicationIdArraylist.get(position));

             JSONArray firstarray = firstObject.getJSONArray("Authors");
             int len = firstarray.length();
             author = new String[len];

             for (int j = 0; j < firstarray.length(); j++) {
                JSONObject third = firstarray.getJSONObject(j);
                author[j] = authorname = third.getString("AuthorName");
             }
             try {
                holder.twtdata.setText(author[0] + ", " + author[1]);
             } 
             catch (Exception e) {              
             }
       } 
       catch (Exception e) {
               e.printStackTrace();
       }
       holder.download.setTag(position);

       holder.download.setOnClickListener(new OnClickListener() {

              public void onClick(View v) {

                 pos = (Integer) v.getTag();
                 Log.d("*******************************", "" + pos);
                 buttonStates[pos] = 1;
                 v.setBackgroundResource(R.drawable.right);
                 selId = Constant.publicationIdArraylist.get(position);
                 System.out.println("buton clicked id  " + selId);
                 try {
                     new PubDetailsTask().execute("");
                 }
                                 catch (Exception e) {
                 }
             }
       });
       return vi;
}

Thanks.

推荐答案

Lets say you have CustomAdapter.class to populate your listview,then:

public class CustomAdapter extends ArrayAdapter<String> {

        String[] array;
    Context mContext;
    LayoutInflater mInflater;
    int[] buttonStates;

    public CustomAdapter(Context context, int textViewResourceId,
            String[] objects)
    {
        super(context, textViewResourceId, objects);
        array=objects;
        mContext=context;
        mInflater = LayoutInflater.from(context);
        //save all buttons state as 0(not clicked) initially
        buttonStates=new int[objects.length];
            for(int i=0;i<objects.length;i++)
            { 
                   buttonStates[i]=0;
            }  
    }  
    @Override
    public View getView(int position, View convertView, ViewGroup parent)
    {
        ...
         if(buttonStates[position]==0)
         {
             holder.button.setBackgroundResource(R.drawable.bg_normal);  //set background for button "not clicked"          
         }
         else
         {
             holder.button.setBackgroundResource(R.drawable.bg_pressed);  //set background for button "clicked"                 
         }

         final int pos=position;
         holder.download.setOnClickListener(new OnClickListener() {

            public void onClick(View v) {

                buttonStates[pos]=1;                
                holder.button.setBackgroundResource(R.drawable.bg_clicked);                
            }
        });         
    }  
}

I have tested this one and it works fine for me!

EDIT :

You need to add these lines of code:

if (buttonStates[position] == 0)
         holder.download.setBackgroundResource(R.drawable.downloadicon); // set background for button "not clicked"             
else
         holder.download.setBackgroundResource(R.drawable.right); // set background for button "clicked"

out side if(convertView == null)...else.... So put that code just before you write:

holder.download.setOnClickListener(new OnClickListener() {
...}

That will solve your issue.

When you put it into if(convertView==null),it will called only once.so you are getting the problem you described to me in your comment!

其他推荐答案

In getView we always recreate view , so how you can expect that a button will store its previous state even after getView called again . so store states inside an array for every button and setBackgroundcolor according to this array inside getView() itself .