Search code examples
androidandroid-listviewonclicklisteneronitemselectedlistener

can we have both of Button and onItemClick listener in ListView in android?


I have Button in each row of ListView and onClickListener for Button. I want to add onItemSelectListener to my ListView too. Is it possible? If yes how can I do that?
Any help will be appreciated.


Solution

  • Yes it is possible ...

    While creating custom view adapter for listview, u have to add onclicklistener on button and u can also need to add onItemSelectListener on Listview. It would work.

    use listview code as

    listView = (ListView) findViewById(R.id.listView2);
          listView .setAdapter(new CustomListAdapter (this,userIDArr));
    
    
          listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
              @Override
              public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
    
                  Toast.makeText(Activity.this,
                            "Item in position " + position + " clicked", Toast.LENGTH_LONG).show();
              }
            });
    

    and create adapter like

    public class CustomListAdapter extends ArrayAdapter<String>
    {
        Activity context;
        public CustomListAdapter (Activity context, ArrayList<String> names) {
            super(context, R.layout.list_item, names);
            this.context = context;
        }
        private class ViewHolder {
    
            public TextView Description;
            public Button  UploadBtn;
        }
    
        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder;
            View rowView = convertView;
            if (rowView == null) {
                LayoutInflater inflater = context.getLayoutInflater();
                rowView = inflater.inflate(R.layout.list_item, null, true);
                holder = new ViewHolder();
    
                holder.Description = (TextView) rowView.findViewById(R.id.User_status);
                holder.UploadBtn = (Button) rowView.findViewById(R.id.uploadbutton);
                holder.UploadBtn.setOnClickListener(new View.OnClickListener() {  
    
                        public void onClick(View v) {  
                        Toast.makeText(Activity.this," Button clicked",Toast.LENGTH_SHORT).show();
                        }   
                    }); 
                    rowView.setTag(holder);
            } else {
                holder = (ViewHolder) rowView.getTag();
            }
    
            holder.Description.setText("U r in middle");
            return rowView;
        }
    }
    

    Now to handle click inside a list item use the below code

    android:focusable="false"
    android:focusableInTouchMode="false"
    

    set these lines while creating Button tag

    It would work ... Please let me know your feedback..