Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- public class NestedAdapter extends BaseAdapter {
- private ArrayList<Pair<Adapter, String>> adapters;
- private Context context;
- public NestedAdapter(Context context, Pair<Adapter, String>... adapters) {
- this.context = context;
- this.adapters = new ArrayList<Pair<Adapter, String>>();
- }
- public void addAdapter(Adapter adapter, String title) {
- adapters.add(new Pair<Adapter, String>(adapter, title));
- }
- private int getAdapterSize(Pair<Adapter, String> pair) {
- if(pair.second==null) {
- return pair.first.getCount();
- } else {
- return pair.first.getCount()+1;
- }
- }
- @Override
- public int getCount() {
- int count = 0;
- for(Pair<Adapter, String> pair: adapters) {
- count += getAdapterSize(pair);
- }
- return count;
- }
- @Override
- public Object getItem(int position) {
- Pair<Adapter, Object> pair = getItemWithAdapter(position);
- if(pair.second instanceof String) {
- return pair.second;
- } else {
- return pair.first.getItem((Integer) pair.second);
- }
- }
- private Pair<Adapter, Object> getItemWithAdapter(int position) {
- int sum = 0;
- int adapterId = 0;
- while(sum<=position) {
- sum += getAdapterSize(adapters.get(adapterId));
- adapterId++;
- }
- adapterId--;
- sum -= getAdapterSize(adapters.get(adapterId));
- int index = position - sum;
- Pair<Adapter, String> pair = adapters.get(adapterId);
- if(pair.second==null) {
- return new Pair<Adapter, Object>(pair.first, index);
- } if(index==0) {
- return new Pair<Adapter, Object>(pair.first, pair.second);
- } else {
- return new Pair<Adapter, Object>(pair.first, index - 1);
- }
- }
- @Override
- public long getItemId(int position) {
- return position;
- }
- @Override
- public View getView(int position, View convertView, ViewGroup parent) {
- Pair<Adapter, Object> itemPair = getItemWithAdapter(position);
- Object second = itemPair.second;
- if(second instanceof String) {
- View view = LayoutInflater.from(context).inflate(android.R.layout.simple_list_item_1, parent, false);
- ((TextView)view.findViewById(android.R.id.text1)).setText((String) second);
- return view;
- } else {
- int index = (Integer) second;
- return itemPair.first.getView(index, convertView, parent);
- }
- }
- }
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement