Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button events in listview

Tags:

android

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.

like image 220
Greek Fire Avatar asked Feb 11 '26 09:02

Greek Fire


2 Answers

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 .

like image 183
Shailendra Singh Rajawat Avatar answered Feb 15 '26 05:02

Shailendra Singh Rajawat


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!

like image 31
Hiral Vadodaria Avatar answered Feb 15 '26 05:02

Hiral Vadodaria



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!