Search code examples
androidandroid-listviewandroid-arrayadaptertogglebutton

how to programmatically add ToggleButton to specific listView


I know how to add a ToggleButton to ALL of the listView rows. But how do i add a ToggleButton to only ONE specific listView row?

Im populating my listView with an ArrayAdapter like so

ListView mlistView = (ListView) findViewById(R.id.listViewSetting);
mlistView.setAdapter(new ArrayAdapter<String>(this,
          android.R.layout.simple_list_item_1,
          new String[] {"Rate @ME App", "Feedback", "Block", "Terms of Service", "Push Notifications", "Sign Out"}));

Solution

    1. Create a layout file containing a togglebutton
    2. Create a customAdapter by extending an Adapter e.g. ArrayAdapter
    3. Override the getView() method
    4. Implement the viewHolder pattern to improve performance
    5. Add logic to the getView() method to handle the togglebutton

    Here is some pseudocode

        @Override
        public View getView(final int position, final View convertView, final ViewGroup parent) {
             // Do inflation here, use a viewholder pattern to improve performance
    
             // Add logic to handle togglebutton, view being togglebutton
             if(items.get(position).equals(something){
                view.setVisibilty(View.Visible);
             }else{
                 view.setVisibilty(View.GONE);
             }
         }