categorise listView items into different sections

2019-03-03 17:43发布

问题:

in my listView i'm trying to divide (categorize) my data in to different section say i have a list of states and i wanna categorize them according to their Countries but what i have right now is categorizing my data Alphabetically and i have no clue how it is happening and how can i achieve what i want. can anyone guide me here ?

my adapter :

public class MyAdapter extends BaseAdapter implements StickyListHeadersAdapter {

private String[] countries;
private LayoutInflater inflater;
private  ArrayList<States> statesArray;



public MyAdapter(Context context , ArrayList<States> states) {
    inflater = LayoutInflater.from(context);
    satesArray = states;
    countries = context.getResources().getStringArray(R.array.all_countries);
}

@Override
public int getCount() {
    return statesArray.size();
}

@Override
public Object getItem(int position) {
    return statesArray.get(position).getName();
}

@Override
public long getItemId(int position) {
    return position;
}

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    ViewHolder holder;

    if (convertView == null) {
        holder = new ViewHolder();
        convertView = inflater.inflate(R.layout.list_view_row, parent, false);
        holder.text = (TextView) convertView.findViewById(R.id.listViewTextView);
        convertView.setTag(holder);
    } else {
        holder = (ViewHolder) convertView.getTag();
    }

    holder.text.setText(statesArray.get(position).getName());


    return convertView;
}

@Override
public View getHeaderView(int position, View convertView, ViewGroup parent) {
    HeaderViewHolder holder;
    if (convertView == null) {
        holder = new HeaderViewHolder();
        convertView = inflater.inflate(R.layout.sticky_header, parent, false);
        holder.text = (TextView) convertView.findViewById(R.id.text1);
        convertView.setTag(holder);
    } else {
        holder = (HeaderViewHolder) convertView.getTag();
    }
    //set header text as first char in name

    String headerText = "" + countries[position];
    holder.text.setText(headerText);
    return convertView;
}

@Override
public long getHeaderId(int position) {
   // return the first character of the country as ID because this is what headers are based upon

    return satesArray.get(position).getName().subSequence(0, 1).charAt(0);
}

class HeaderViewHolder {
    TextView text;
}

class ViewHolder {
    TextView text;
}

}

UPDATE :

what i want is right here but instead of Alphabets at Section there would be Country name and at rows there would be states of respective Country :

righ here