一、首先我们想要的效果是:
在城市索引的列表能够加个自定义头部;
有城市索引的字母悬浮块;
右侧的字母索引导航;
仿ios效果的当前位置索引提示框
我们先来看下效果:
这里写图片描述
下面的代码可能有点多,但是效果却很不错,请耐心往下看
这里我是用的IndexableLayout控件做的
如果还是有不清楚的,可以去看我的Demo:CityProject
博客地址:点击这里
二、如何使用IndexableLayout:
需要加入第三方依赖库:
implementation 'me.yokeyword:indexablerecyclerview:1.3.0'
在.xml布局中:
android:id="@+id/indexableLayout"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="@android:color/white"
app:indexBar_selectedTextColor="@color/black" //右侧导航选中时的颜色
app:indexBar_textColor="@color/gray1" //右侧导航字体颜色
app:indexBar_layout_width="40dp" //右侧导航的宽度
app:indexBar_textSize="14sp" //右侧导航的字体大小
app:indexBar_textSpace="5dp" />
在Activity中:
下面注释写的很清楚了,这里我就不多做说明了
public class CityPickerActivity extends AppCompatActivity {
//IndexableLayout 的适配器
private ContactAdapter mAdapter;
//自定义头部adapter
private BannerHeaderAdapter mBannerHeaderAdapter;
//热门城市的数组
private String[] city = {"东莞","深圳","广州","温州","郑州","金华","佛山","上海","苏州","杭州","长沙","中山"};
private IndexableLayout indexableLayout;
//热门城市的适配器
private CYBChangeCityGridViewAdapter cybChangeCityGridViewAdapter;
热门城市的集合
private ArrayList list;
//返回按钮
private ImageView pic_contact_back;
private Intent intent;
@Override
protected void onCreate(@Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pick_contact);
initview();
initAdapter();
onlisten();
}
public void initAdapter(){
mAdapter = new ContactAdapter(this);
indexableLayout.setAdapter(mAdapter);
//设置字母提示框为仿os居中
indexableLayout.setOverlayStyle_Center();
mAdapter.setDatas(initDatas());
// indexableLayout.setOverlayStyle_MaterialDesign(Color.RED); 设置提示框为仿联系人气泡样式
// 全字母排序。 排序规则设置为:每个字母都会进行比较排序;速度较慢
indexableLayout.setCompareMode(IndexableLayout.MODE_FAST);
// indexableLayout.addHeaderAdapter(new SimpleHeaderAdapter<>(mAdapter, "☆",null, null));
// 构造函数里3个参数,分别对应 (IndexBar的字母索引, IndexTitle, 数据源), 不想显示哪个就传null, 数据源传null时,代表add一个普通的View
// mMenuHeaderAdapter = new MenuHeaderAdapter("↑", null, initMenuDatas());
// indexableLayout.addHeaderAdapter(mMenuHeaderAdapter);
// 这里BannerView只有一个Item, 添加一个长度为1的任意List作为第三个参数
List bannerList = new ArrayList<>();
bannerList.add("");
mBannerHeaderAdapter = new BannerHeaderAdapter("↑", null, bannerList);
indexableLayout.addHeaderAdapter(mBannerHeaderAdapter);
}
public void initview(){
intent = getIntent();
pic_contact_back = (ImageView) findViewById(R.id.pic_contact_back);
indexableLayout = (IndexableLayout) findViewById(R.id.indexableLayout);
indexableLayout.setLayoutManager(new LinearLayoutManager(this));
}
public void onlisten(){
pic_contact_back.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
finish();
}
});
mAdapter.setOnItemCo