安卓A-Z城市列表排序

版权声明:本文为博主原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。
本文链接:https://blog.csdn.net/qq_34536167/article/details/80867967

前言:上一篇是ListView写的这次换成RecyclerView来,并且扩展性更加高些

链接:https://blog.csdn.net/qq_34536167/article/details/78241092

首先build.gradle:加入

 //拼音解析
    implementation 'com.belerweb:pinyin4j:2.5.1'

1、效果图:

这里写图片描述

这里写图片描述

2、项目结构:

这里写图片描述

3、MainActivity:

import android.os.Bundle;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.widget.TextView;
import android.widget.Toast;

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class MainActivity extends AppCompatActivity {

    private RecyclerView recyclerCity;
    private TextView dialog;
    private SideBar sidebar;

    private List<Object> objects;
    private List<CityDto.CityDetails.DataCity> list1;
    private List<CityDto.CityDetails.DataCity> list2;
    private List<CityDto.CityDetails.DataCity> list3;
    private List<CityDto.CitySortDetails.CitySortDto> list4;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        recyclerCity = this.findViewById(R.id.recycler_city);
        dialog = this.findViewById(R.id.dialog);
        sidebar = this.findViewById(R.id.sidebar);

        initData();
    }

    private void initData() {
        if (null == objects) {
            objects = new ArrayList<>();
        }
        if (null == list1) {
            list1 = new ArrayList<>();
        } else {
            list1.clear();
        }
        if (null == list2) {
            list2 = new ArrayList<>();
        } else {
            list2.clear();
        }
        if (null == list3) {
            list3 = new ArrayList<>();
        } else {
            list3.clear();
        }
        if (null == list4) {
            list4 = new ArrayList<>();
        } else {
            list4.clear();
        }

        CityDto.CityDetails orderDetails1 = new CityDto.CityDetails();
        CityDto.CityDetails orderDetails2 = new CityDto.CityDetails();
        CityDto.CityDetails orderDetails3 = new CityDto.CityDetails();
        CityDto.CityDetails.DataCity detailsList1 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList2 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList3 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList4 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList5 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList6 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList7 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList8 = new CityDto.CityDetails.DataCity();
        CityDto.CityDetails.DataCity detailsList9 = new CityDto.CityDetails.DataCity();

        CityDto.CitySortDetails orderDetails4 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails5 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails6 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails7 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails8 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails9 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails10 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails11 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails12 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails13 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails14 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails15 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails16 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails17 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails18 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails19 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails20 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails21 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails22 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails23 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails24 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails25 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails26 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails27 = new CityDto.CitySortDetails();
        CityDto.CitySortDetails orderDetails28 = new CityDto.CitySortDetails();

        detailsList1.setCityName("重庆");
        detailsList2.setCityName("湖北");
        detailsList3.setCityName("湖南");
        detailsList4.setCityName("河北");
        detailsList5.setCityName("四川");
        detailsList6.setCityName("天津");
        detailsList7.setCityName("吉林");
        detailsList8.setCityName("黑龙");
        detailsList9.setCityName("江西");

        list4.add(new CityDto.CitySortDetails.CitySortDto("广东"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("北京"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("福建"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("浙江"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("山东"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("江苏"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("河南"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("安徽"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("重庆"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("湖北"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("湖南"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("河北"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("四川"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("天津"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("吉林"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("黑龙"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("江西"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("辽宁"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("内蒙"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("宁夏"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("青海"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("山西"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("陕西"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("上海"));
        list4.add(new CityDto.CitySortDetails.CitySortDto("新疆"));

        list1.add(detailsList1);
        list1.add(detailsList2);
        list1.add(detailsList3);
        list1.add(detailsList4);
        list2.add(detailsList5);
        list2.add(detailsList6);
        list3.add(detailsList7);
        list3.add(detailsList8);
        list3.add(detailsList9);
        orderDetails1.setLocation("江西省赣州市");
        orderDetails1.setCityList(list1);
        orderDetails2.setCityList(list2);
        orderDetails3.setCityList(list3);

        orderDetails4.setCitySortDtos(list4);
        orderDetails5.setCitySortDtos(list4);
        orderDetails6.setCitySortDtos(list4);
        orderDetails7.setCitySortDtos(list4);
        orderDetails8.setCitySortDtos(list4);
        orderDetails9.setCitySortDtos(list4);
        orderDetails10.setCitySortDtos(list4);
        orderDetails11.setCitySortDtos(list4);
        orderDetails12.setCitySortDtos(list4);
        orderDetails13.setCitySortDtos(list4);
        orderDetails14.setCitySortDtos(list4);
        orderDetails15.setCitySortDtos(list4);
        orderDetails16.setCitySortDtos(list4);
        orderDetails17.setCitySortDtos(list4);
        orderDetails18.setCitySortDtos(list4);
        orderDetails19.setCitySortDtos(list4);
        orderDetails20.setCitySortDtos(list4);
        orderDetails21.setCitySortDtos(list4);
        orderDetails22.setCitySortDtos(list4);
        orderDetails23.setCitySortDtos(list4);
        orderDetails24.setCitySortDtos(list4);
        orderDetails25.setCitySortDtos(list4);
        orderDetails26.setCitySortDtos(list4);
        orderDetails27.setCitySortDtos(list4);
        orderDetails28.setCitySortDtos(list4);

        objects.add(orderDetails1);
        objects.add(orderDetails2);
        objects.add(orderDetails3);

        objects.add(orderDetails4);
        objects.add(orderDetails5);
        objects.add(orderDetails6);
        objects.add(orderDetails7);
        objects.add(orderDetails8);
        objects.add(orderDetails9);
        objects.add(orderDetails10);
        objects.add(orderDetails11);
        objects.add(orderDetails12);
        objects.add(orderDetails13);
        objects.add(orderDetails14);
        objects.add(orderDetails15);
        objects.add(orderDetails16);
        objects.add(orderDetails17);
        objects.add(orderDetails18);
        objects.add(orderDetails19);
        objects.add(orderDetails20);
        objects.add(orderDetails21);
        objects.add(orderDetails22);
        objects.add(orderDetails23);
        objects.add(orderDetails24);
        objects.add(orderDetails25);
        objects.add(orderDetails26);
        objects.add(orderDetails27);
        objects.add(orderDetails28);

        //排序
        list4 = Tools.filledData(list4, sidebar);
        Collections.sort(list4, new PinyinComparator());
        final CityAdapter adapter = new CityAdapter(this, objects, list4);
        final LinearLayoutManager manager = new LinearLayoutManager(this);
        recyclerCity.setLayoutManager(manager);
        recyclerCity.setAdapter(adapter);
        sidebar.setTextView(dialog);
        sidebar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
                //该字母首次出现的位置
                int position = adapter.getPositionForSection(s.charAt(0));
                if (position != -1) {
                    Tools.moveToPosition(manager, position + 3);
                }
                Log.e("触摸的位置:", position + "");
            }
        });
        adapter.setListener(new CityAdapter.MoveToZeroListener() {
            @Override
            public void cityName(String cityName) {
                Toast.makeText(MainActivity.this, cityName, Toast.LENGTH_LONG).show();
            }
        });
    }
}

4、CityAdapter:

public class CityAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {

    //所有要展示的数据源object集合
    private List<Object> objects;

    private static final int TYPE_ITEM_INFO = 0X123;
    private static final int TYPE_ITEM_CITY = 0X124;

    private Context mContext;

    private List<CityDto.CitySortDetails.CitySortDto> list = null;

    public CityAdapter(Context context, List<Object> objects, List<CityDto.CitySortDetails.CitySortDto> list) {
        this.mContext = context;
        this.objects = objects;
        this.list = list;
    }

    /**
     * 基于项不同的类型来获得不同的viewholder,关联对应的布局
     *
     * @return
     */
    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
        RecyclerView.ViewHolder viewHolder = null;
        switch (viewType) {
            case TYPE_ITEM_INFO:
                viewHolder = new DetailsHolder(inflate(parent, R.layout.item_city_list));
                break;
            case TYPE_ITEM_CITY:
                viewHolder = new CityHolder(inflate(parent, R.layout.item_sort_city));
                break;
        }
        return viewHolder;
    }

    /**
     * 关联布局
     */
    private View inflate(ViewGroup parent, int resId) {
        return LayoutInflater.from(parent.getContext()).inflate(resId, parent, false);
    }


    @Override
    public void onBindViewHolder(RecyclerView.ViewHolder holder, int position) {
        Object object = objects.get(position);
        switch (holder.getItemViewType()) {
            case TYPE_ITEM_INFO://当前、定位、热门
                setTypeItemDetail((DetailsHolder) holder, (CityDto.CityDetails) object, position);
                break;
            case TYPE_ITEM_CITY://城市排序
                setTypeCityDetail((CityHolder) holder, position);
                break;
        }
    }

    @Override
    public int getItemCount() {
        return objects == null ? 0 : objects.size();
    }

    /**
     * 获得每个项的类型
     *
     * @param position
     * @return
     */
    @Override
    public int getItemViewType(int position) {

        Object object = objects.get(position);
        if (object instanceof CityDto.CityDetails) {
            return TYPE_ITEM_INFO;
        } else if (object instanceof CityDto.CitySortDetails) {
            return TYPE_ITEM_CITY;
        }
        return super.getItemViewType(position);
    }

    /**
     * 设置当前、定位、热门
     *
     * @param holder       DetailsHolder
     * @param orderDetails 实体
     */
    private void setTypeItemDetail(final DetailsHolder holder, final CityDto.CityDetails orderDetails, final int position) {

        CityItemAdapter adapter = new CityItemAdapter(mContext, orderDetails.getCityList());
        holder.recyclerList.setLayoutManager(new GridLayoutManager(mContext, 3));
        holder.recyclerList.setAdapter(adapter);
        adapter.setOnItemClickListener(new CommonRecyclerAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(RecyclerView parent, View view, int position) {
                listener.cityName(orderDetails.getCityList().get(position).getCityName());
            }
        });
        if (position == 0) {
            String location = orderDetails.getLocation();
            holder.cityTypeTitle.setText("当前:" + location);
        } else if (position == 1) {
            holder.cityTypeTitle.setText("定位最近访问");
        } else if (position == 2) {
            holder.cityTypeTitle.setText("热门城市");
        }
    }


    class DetailsHolder extends RecyclerView.ViewHolder {

        private RecyclerView recyclerList;
        private TextView cityTypeTitle;

        public DetailsHolder(View itemView) {
            super(itemView);
            recyclerList = itemView.findViewById(R.id.recycler_list);
            cityTypeTitle = itemView.findViewById(R.id.city_type_title);
        }
    }

    /**
     * 设置城市排序
     *
     * @param holder CityHolder
     */
    private void setTypeCityDetail(CityHolder holder, int position) {

        //注意此处position-3.因为前面已经有3个对象
        final int selectPosition = position - 3;

        int section = getSectionForPosition(selectPosition);
        //获取选中的位置
        if (selectPosition == getPositionForSection(section)) {
            holder.tvCatagory.setVisibility(View.VISIBLE);
            //首字母
            holder.tvCatagory.setText(list.get(selectPosition).getSortLetters());
        } else {
            holder.tvCatagory.setVisibility(View.GONE);
        }
        //城市名
        holder.tvCityName.setText((list.get(selectPosition).getName()));
        holder.tvCityName.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                listener.cityName(list.get(selectPosition).getName());
            }
        });

    }

    public int getSectionForPosition(int position) {
        return list.get(position).getSortLetters().charAt(0);
    }

    public int getPositionForSection(int sectionIndex) {
        for (int i = 0; i < list.size(); i++) {
            String sortStr = list.get(i).getSortLetters();
            char firstChar = sortStr.toUpperCase().charAt(0);
            if (firstChar == sectionIndex) {
                return i;
            }
        }
        return -1;
    }

    class CityHolder extends RecyclerView.ViewHolder {

        private TextView tvCityName;
        private TextView tvCatagory;

        public CityHolder(View itemView) {
            super(itemView);
            tvCityName = itemView.findViewById(R.id.tv_city_name);
            tvCatagory = itemView.findViewById(R.id.tv_catagory);
        }
    }

    private MoveToZeroListener listener;

    public void setListener(MoveToZeroListener listener) {
        this.listener = listener;
    }

    /**
     * 将城市名回调给activity
     */
    public interface MoveToZeroListener {

        void cityName(String cityName);

    }
}

5、CityDto:

public class CityDto {

    public static class CityDetails {

        private String location;

        public String getLocation() {
            return location;
        }

        public void setLocation(String location) {
            this.location = location;
        }

        private List<DataCity> cityList;

        public List<DataCity> getCityList() {
            return cityList;
        }

        public void setCityList(List<DataCity> cityList) {
            this.cityList = cityList;
        }

        public static class DataCity {

            private String cityName;

            public String getCityName() {
                return cityName;
            }

            public void setCityName(String cityName) {
                this.cityName = cityName;
            }

            public DataCity(String cityName) {
                this.cityName = cityName;
            }

            public DataCity() {
            }
        }
    }

    public static class CitySortDetails {

        private List<CitySortDto> citySortDtos;

        public List<CitySortDto> getCitySortDtos() {
            return citySortDtos;
        }

        public void setCitySortDtos(List<CitySortDto> citySortDtos) {
            this.citySortDtos = citySortDtos;
        }

        public static class CitySortDto {

            private String name;//显示的数据
            private String sortLetters;//显示数据拼音的首字母

            public String getName() {
                return name;
            }

            public void setName(String name) {
                this.name = name;
            }

            public String getSortLetters() {
                return sortLetters;
            }

            public void setSortLetters(String sortLetters) {
                this.sortLetters = sortLetters;
            }

            public CitySortDto() {
            }

            public CitySortDto(String name) {
                this.name = name;
            }
        }
    }
}

6、CityItemAdapter:

public class CityItemAdapter extends CommonRecyclerAdapter<CityDto.CityDetails.DataCity> {

    public CityItemAdapter(Context context, List<CityDto.CityDetails.DataCity> list) {
        super(context, R.layout.item_city_name, list);
    }

    @Override
    public void convert(RecyclerHolder holder, CityDto.CityDetails.DataCity item, int position) {

        //城市名
        String name = item.getCityName();
        holder.setText(R.id.item_city_name, name);
    }
}

注意:CommonRecyclerAdapter原来文章写过

7、PinyinComparator:

import java.util.Comparator;

/**
 * 功能描述:对数据根据A-Z进行排序,前面两个if判断主要是将不是以汉字开头的数据放在后面
 */
public class PinyinComparator implements Comparator<CityDto.CitySortDetails.CitySortDto> {

    public int compare(CityDto.CitySortDetails.CitySortDto o1, CityDto.CitySortDetails.CitySortDto o2) {
        //这里主要是用来对ListView里面的数据根据ABCDEFG...来排序
        if (o1.getSortLetters().equals("@")
                || o2.getSortLetters().equals("#")) {
            return -1;
        } else if (o1.getSortLetters().equals("#")
                || o2.getSortLetters().equals("@")) {
            return 1;
        } else {
            return o1.getSortLetters().compareTo(o2.getSortLetters());
        }
    }

}

8、PinyinUtils:

public class PinyinUtils {

    /**
     * 将字符串中的中文转化为拼音,英文字符不变
     *
     * @param inputString 汉字
     * @return
     */
    public static String getPingYin(String inputString) {
        HanyuPinyinOutputFormat format = new HanyuPinyinOutputFormat();
        format.setCaseType(HanyuPinyinCaseType.LOWERCASE);
        format.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
        format.setVCharType(HanyuPinyinVCharType.WITH_V);
        String output = "";
        if (inputString != null && inputString.length() > 0
                && !"null".equals(inputString)) {
            char[] input = inputString.trim().toCharArray();
            try {
                for (int i = 0; i < input.length; i++) {
                    if (java.lang.Character.toString(input[i]).matches(
                            "[\\u4E00-\\u9FA5]+")) {
                        String[] temp = PinyinHelper.toHanyuPinyinStringArray(
                                input[i], format);
                        output += temp[0];
                    } else
                        output += java.lang.Character.toString(input[i]);
                }
            } catch (BadHanyuPinyinOutputFormatCombination e) {
                e.printStackTrace();
            }
        } else {
            return "*";
        }
        return output;
    }
}

9、SideBar:

public class SideBar extends View {

    public static String[] INDEX_STRING = {"A", "B", "C", "D", "E", "F", "G", "H", "I",
            "J", "K", "L", "M", "N", "O", "P", "Q", "R", "S", "T", "U", "V",
            "W", "X", "Y", "Z"};

    private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
    private List<String> letterList;
    private int choose = -1;
    private Paint paint = new Paint();
    private TextView mTextDialog;

    public SideBar(Context context) {
        this(context, null);
    }

    public SideBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public SideBar(Context context, AttributeSet attrs, int defStyle) {
        super(context, attrs, defStyle);
        init();
    }

    private void init() {
        setBackgroundColor(Color.parseColor("#F0F0F0"));
        letterList = Arrays.asList(INDEX_STRING);
    }

    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);
        int height = getHeight();// 获取对应高度
        int width = getWidth();// 获取对应宽度
        int singleHeight = height / letterList.size();// 获取每一个字母的高度
        for (int i = 0; i < letterList.size(); i++) {
            paint.setColor(Color.parseColor("#606060"));
            paint.setTypeface(Typeface.DEFAULT_BOLD);
            paint.setAntiAlias(true);
            paint.setTextSize(30);
            // 选中的状态
            if (i == choose) {
                paint.setColor(Color.parseColor("#ffffff"));//选中文字颜色
                paint.setFakeBoldText(true);
            }
            // x坐标等于中间-字符串宽度的一半.
            float xPos = width / 2 - paint.measureText(letterList.get(i)) / 2;
            float yPos = singleHeight * i + singleHeight / 2;
            canvas.drawText(letterList.get(i), xPos, yPos, paint);
            paint.reset();// 重置画笔
        }
    }

    @Override
    public boolean dispatchTouchEvent(MotionEvent event) {
        final int action = event.getAction();
        final float y = event.getY();// 点击y坐标
        final int oldChoose = choose;
        final OnTouchingLetterChangedListener listener = onTouchingLetterChangedListener;
        final int c = (int) (y / getHeight() * letterList.size());// 点击y坐标所占总高度的比例*b数组的长度就等于点击b中的个数.

        switch (action) {
            case MotionEvent.ACTION_UP:
                setBackgroundColor(Color.parseColor("#F0F0F0"));
                choose = -1;
                invalidate();
                if (mTextDialog != null) {
                    mTextDialog.setVisibility(View.GONE);
                }
                break;
            default:
                setBackgroundResource(R.drawable.sidebar_background);
                if (oldChoose != c) {
                    if (c >= 0 && c < letterList.size()) {
                        if (listener != null) {
                            listener.onTouchingLetterChanged(letterList.get(c));
                        }
                        if (mTextDialog != null) {
                            mTextDialog.setText(letterList.get(c));
                            mTextDialog.setVisibility(View.VISIBLE);
                        }
                        choose = c;
                        invalidate();
                    }
                }
                break;
        }
        return true;
    }

    public void setIndexText(ArrayList<String> indexStrings) {
        this.letterList = indexStrings;
        invalidate();
    }

    /**
     * 为SideBar设置显示当前按下的字母的TextView
     *
     * @param mTextDialog
     */
    public void setTextView(TextView mTextDialog) {
        this.mTextDialog = mTextDialog;
    }

    /**
     * 向外公开的方法
     *
     * @param onTouchingLetterChangedListener
     */
    public void setOnTouchingLetterChangedListener(
            OnTouchingLetterChangedListener onTouchingLetterChangedListener) {
        this.onTouchingLetterChangedListener = onTouchingLetterChangedListener;
    }

    /**
     * 接口
     */
    public interface OnTouchingLetterChangedListener {
        void onTouchingLetterChanged(String s);
    }

}

10、Tools:

public class Tools {

    /**
     * 先对乱序list进行排序
     *
     * @param date
     * @return
     */
    public static List<CityDto.CitySortDetails.CitySortDto> filledData(List<CityDto.CitySortDetails.CitySortDto> date, SideBar sideBar) {
        List<CityDto.CitySortDetails.CitySortDto> mSortList = new ArrayList<>();
        ArrayList<String> indexString = new ArrayList<>();
        //遍历需要排序的list
        for (int i = 0; i < date.size(); i++) {
            //实例化
            CityDto.CitySortDetails.CitySortDto sortModel = new CityDto.CitySortDetails.CitySortDto();
            //讲名字set进实体中
            sortModel.setName(date.get(i).getName());
            //获得城市名的首字母(中文转英文)
            String pinyin = PinyinUtils.getPingYin(date.get(i).getName());
            //截取第一位即可,并转化为大写字母
            String sortString = pinyin.substring(0, 1).toUpperCase();
            //判断字母是否在A-Z之中
            if (sortString.matches("[A-Z]")) {
                //并添加到是实体中
                sortModel.setSortLetters(sortString.toUpperCase());
                //新的list不包含才添加
                if (!indexString.contains(sortString)) {
                    indexString.add(sortString);
                }
            }
            mSortList.add(sortModel);
        }
        Collections.sort(indexString);
        sideBar.setIndexText(indexString);
        return mSortList;
    }

    /**
     * RecyclerView 移动到当前位置,
     *
     * @param manager 设置RecyclerView对应的manager
     * @param n       要跳转的位置
     */
    public static void moveToPosition(LinearLayoutManager manager, int n) {
        manager.scrollToPositionWithOffset(n, 0);//当前的manager
        manager.setStackFromEnd(true);//让最后添加的item始终显示在RecycleView中
    }
}

11、布局文件:

activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <FrameLayout
        android:layout_width="match_parent"
        android:layout_height="match_parent">

        <android.support.v7.widget.RecyclerView
            android:id="@+id/recycler_city"
            android:layout_width="match_parent"
            android:layout_height="match_parent" />

        <TextView
            android:id="@+id/dialog"
            android:layout_width="80dp"
            android:layout_height="80dp"
            android:layout_gravity="center"
            android:background="#666"
            android:gravity="center"
            android:text="A"
            android:textColor="#fff"
            android:textSize="50sp"
            android:visibility="gone"
            tools:visibility="visible" />

        <com.helloword.SideBar
            android:id="@+id/sidebar"
            android:layout_width="30dp"
            android:layout_height="match_parent"
            android:layout_gravity="right|center"
            android:layout_marginBottom="25dp"
            android:layout_marginTop="40dp"
            android:background="@drawable/sidebar_background" />
    </FrameLayout>
</LinearLayout>

item_city_list.xml

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical">

    <TextView
        android:id="@+id/city_type_title"
        style="@style/tech_sort"
        android:padding="5dp"
        android:text="" />

    <android.support.v7.widget.RecyclerView
        android:id="@+id/recycler_list"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:paddingBottom="5dp"
        android:paddingLeft="15dp"
        android:paddingRight="15dp"
        android:paddingTop="5dp" />

    <View
        android:id="@+id/item_line_second"
        style="@style/my_line_style" />

</LinearLayout>

item_city_name.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:gravity="center"
    android:layout_height="wrap_content"
    android:layout_margin="10dp">

    <TextView
        android:id="@+id/item_city_name"
        style="@style/city_item"
        android:text="深圳" />

</LinearLayout>

item_sort_city.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:orientation="vertical"
    android:paddingRight="40dp"
    android:paddingLeft="15dp"
    android:background="#f5f5f5">

    <TextView
        android:layout_marginTop="10dp"
        android:id="@+id/tv_catagory"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:gravity="center"
        android:text="A"
        android:textColor="#666666"
        android:textSize="14sp" />


    <TextView
        android:layout_marginTop="10dp"
        android:layout_width="match_parent"
        android:id="@+id/tv_city_name"
        style="@style/city_item"
        android:text="深圳" />

</LinearLayout>

12、资源文件:

city_item_bg.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android">

    <solid
        android:color="@color/white_bg_color"/>

    <corners
        android:radius="5dp"/>

    <stroke
        android:width="0.5dp"
        android:color="#D4D4D4"/>

</shape>

selector_shape.xml:

<?xml version="1.0" encoding="utf-8"?>
<selector xmlns:android="http://schemas.android.com/apk/res/android">

    <item android:drawable="@color/unwhite_bg_color" android:state_pressed="true"/>
    <item android:drawable="@color/white_bg_color" />
</selector>

sidebar_background.xml:

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle" >

    <gradient
        android:angle="90"
        android:endColor="#8F8F8F"
        android:startColor="#8F8F8F" />

    <corners
        android:bottomLeftRadius="5dp"
        android:topLeftRadius="5dp" />

</shape>

颜色值:

   <color name="white_bg_color">#FFFFFF</color>
    <color name="unwhite_bg_color">#E8E8E8</color>

styles.xml样式:

 <!--linear样式-->
    <style name="city_style">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#666</item>
        <item name="android:textSize">14sp</item>
        <item name="android:drawablePadding">5dp</item>
    </style>

    <!-- 分割线 -->
    <style name="my_line_style">
        <item name="android:layout_width">match_parent</item>
        <item name="android:layout_height">0.5dp</item>
        <item name="android:background">#CBCBCB</item>
    </style>

    <!--排序item-->
    <style name="tech_sort">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#969696</item>
        <item name="android:textSize">12sp</item>
    </style>

    <!-- 城市style -->
    <style name="city_item">
        <item name="android:layout_width">wrap_content</item>
        <item name="android:layout_height">wrap_content</item>
        <item name="android:textColor">#454545</item>
        <item name="android:textSize">14sp</item>
        <item name="android:paddingLeft">25dp</item>
        <item name="android:paddingRight">25dp</item>
        <item name="android:paddingTop">5dp</item>
        <item name="android:paddingBottom">5dp</item>
        <item name="android:background">@drawable/city_item_bg</item>
    </style>

如果要增加城市搜索输入功能,可以参考原来的自行扩展

展开阅读全文

没有更多推荐了,返回首页