There is a ListVIew from TextView, I need to add a Switch in the 10 position of the listView between the 10 and 11 elements.

There is such an option to create a layout with TextView and Switcch, Switch initially to make INVISIBLE and after 10 to make VISIBLE. But such an option will seem to affect the performance, since in fact, for the sake of 1 element, I already create N - the number ...

Is there a better option?

    2 answers 2

    1. Create a Switch in code using Java :

       Switch switch = new Switch(context); layout.addView(switch); 
    2. Create a separate Layout in XML with a Switch in case you need one, and do this:

       if(needSwitch) { convertView = inflator.inflate(R.layout.with_switch, null); } else { convertView = inflator.inflate(R.layout.without_switch, null); } 

      Naturally, you have to figure out how to ViewHolder with the ViewHolder

    3. Do the way you came up with - show the switch only when you need it.

    • And why Layout? can ListView.addView? - Andro
    • @xTIGRx, do you need it as a separate list item, or as part of a list item? - Vladyslav Matviienko
    • Well, it turns out that as an item in the ListView. just everywhere TextView and in 10 positions, besides TextVIew, there should be a Switch - Andro
    • @xTIGRx, Switch next to TextVIew in one list item? Or one element - TextVIew , and one more element Switch ? If Switch last should be at all, then for this you can use footer - Vladyslav Matviienko
    • TextView and Switch as one element - Andro

    It is necessary to redefine getItemViewType in the adapter and in getView to return the desired view depending on the type. Below is an example, put it blindly.

     @Override public int getItemViewType(int position) { if (needSwitch) return 1; else return 0; } @Override public View getView(int position, View convertView, ViewGroup parent) { if(getItemViewType(position) == 0) { ViewWithoutSwitch view; if (convertView != null && convertView instanceof ViewWithoutSwitch) { view = (ViewWithoutSwitch) convertView; } else { view = new ViewWithoutSwitch(parent.getContext()); } view.bind(getItem(position)); return view; } else { ViewWithSwitch view; if (convertView != null && convertView instanceof ViewWithSwitch) { view = (ViewWithSwitch) convertView; } else { view = new ViewWithSwitch(parent.getContext()); } view.bind(getItem(position)); return view; } } 

    You can do differently. Make one view and add a Switch there, and through bind set the desired visibility. Be sure to reuse convertView.