Android仿微信实现首字母导航条
作者:zhiwenyan 发布时间:2022-07-16 11:14:29
标签:android,首字母,导航条
本文介绍Android实现首字母导航条,先看张效果图,具体怎么实现看代码吧
具体的步骤
1.整体布局的显示
2. 实现A-Z的分组
3. 自定义A-Z的导航条
4. 中间显示/隐藏触摸到导航条具体的字母
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:background="#fff"
android:orientation="vertical"
tools:context="com.example.firstnavigation.MainActivity">
<FrameLayout
android:layout_width="match_parent"
android:layout_height="wrap_content">
<!--ListView-->
<ListView
android:id="@+id/friend_listview"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<!--中间显示的字母-->
<TextView
android:id="@+id/tv_first"
android:layout_width="80dp"
android:layout_height="80dp"
android:layout_gravity="center"
android:text="A"
android:textColor="#ff0000"
android:textSize="30sp"
android:visibility="gone" />
<!--自定义导航条-->
<com.example.firstnavigation.SlidView
android:id="@+id/slidView"
android:layout_width="30dp"
android:layout_height="match_parent"
android:layout_gravity="right|center" />
</FrameLayout>
</LinearLayout>
item.xml —-》ListView对应item
<?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="match_parent"
android:background="#fff"
android:orientation="vertical">
<!--首字母-->
<TextView
android:id="@+id/tv"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#9e9d9d"
android:textColor="#fff"
android:textSize="16sp" />
<!--首字母对应的首个汉字-->
<TextView
android:id="@+id/name"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#262626"
android:textSize="16sp" />
</LinearLayout>
联系人Bean
public class Contact {
//姓名
private String name;
//姓名的首字母
private String firstWord;
public String getName() {
return name;
}
public void setName(String name) {
this.name = name;
}
public String getFirstWord() {
return firstWord;
}
public void setFirstWord(String ch) {
this.firstWord = ch;
}
}
ContactAdapter.java
public class ContactAdapter extends BaseAdapter {
private ArrayList<Contact> arrayList;
private Context context;
private String pre = "A";
public ContactAdapter(ArrayList<Contact> arrayList, Context context) {
this.arrayList = arrayList;
this.context = context;
}
@Override
public int getCount() {
return arrayList.size();
}
@Override
public Object getItem(int position) {
return arrayList.get(position);
}
@Override
public long getItemId(int position) {
return position;
}
@Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder viewHolder;
if (convertView == null) {
viewHolder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
viewHolder.tv_firstWord = (TextView) convertView.findViewById(R.id.tv);
viewHolder.name = (TextView) convertView.findViewById(R.id.name);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.tv_firstWord.setText(String.valueOf(arrayList.get(position).getFirstWord()));
viewHolder.name.setText(arrayList.get(position).getName());
/**
* 分组:根据汉字的首字母
*/
viewHolder.tv_firstWord.setVisibility(!arrayList.get(position).getFirstWord().equals(pre) ? View.VISIBLE : View.GONE);
pre = arrayList.get(position).getFirstWord();
return convertView;
}
class ViewHolder {
TextView tv_firstWord;
TextView name;
}
MainActivity
public class MainActivity extends AppCompatActivity {
private ListView listView;
private TextView tv_first;
private ArrayList<Contact> contacts;
private SlidView slidView;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
initView();
initData();
}
private void initView() {
listView = (ListView) findViewById(R.id.friend_listview);
tv_first = (TextView) findViewById(R.id.tv_first);
slidView = (SlidView) findViewById(R.id.slidView);
slidView.setFirstListener(new OnTouchFirstListener() {
@Override
public void onTouch(String str) {
tv_first.setVisibility(View.VISIBLE);
tv_first.setText(str);
for (int i = 0; i < contacts.size(); i++) {
if (str.equals(contacts.get(i).getFirstWord())) {
listView.setSelection(i);
}
}
}
@Override
public void onRelease() {
new Handler().postDelayed(new Runnable() {
@Override
public void run() {
tv_first.setVisibility(View.GONE);
}
}, 300);
}
});
}
private void initData() {
contacts = new ArrayList<>();
//获取字符数组资源
String[] attrs = getResources().getStringArray(R.array.myFriend);
Contact contact;
for (int i = 0; i < attrs.length; i++) {
contact = new Contact();
contact.setName(attrs[i]);
contact.setFirstWord(getPinYinHeadChar(attrs[i], 2));
contacts.add(contact);
}
//排序A-Z
Collections.sort(contacts, new Comparator<Contact>() {
@Override
public int compare(Contact lhs, Contact rhs) {
return lhs.getFirstWord().compareTo(rhs.getFirstWord());
}
});
ContactAdapter contactAdapter = new ContactAdapter(contacts, this);
listView.setAdapter(contactAdapter);
}
/**
* 提取汉字的首字母,如果里面含有费中文字符则忽略之;如果全为非中文则返回""。
*
* @param caseType 当为1时获取的首字母为小写,否则为大写。
*/
public static String getPinYinHeadChar(String zn_str, int caseType) {
if (zn_str != null && !zn_str.trim().equalsIgnoreCase("")) {
char[] strChar = zn_str.toCharArray();
// 汉语拼音格式输出类
HanyuPinyinOutputFormat hanYuPinOutputFormat = new HanyuPinyinOutputFormat();
// 输出设置,大小写,音标方式等
if (1 == caseType) {
hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.LOWERCASE);
} else {
hanYuPinOutputFormat.setCaseType(HanyuPinyinCaseType.UPPERCASE);
}
hanYuPinOutputFormat.setToneType(HanyuPinyinToneType.WITHOUT_TONE);
hanYuPinOutputFormat.setVCharType(HanyuPinyinVCharType.WITH_V);
StringBuffer pyStringBuffer = new StringBuffer();
char c = strChar[0];
char pyc;
if (String.valueOf(c).matches("[\\u4E00-\\u9FA5]+")) {//是中文或者a-z或者A-Z转换拼音
try {
String[] pyStirngArray = PinyinHelper.toHanyuPinyinStringArray(strChar[0], hanYuPinOutputFormat);
if (null != pyStirngArray && pyStirngArray[0] != null) {
pyc = pyStirngArray[0].charAt(0);
pyStringBuffer.append(pyc);
}
} catch (BadHanyuPinyinOutputFormatCombination e) {
e.printStackTrace();
}
}
return pyStringBuffer.toString();
}
return null;
}
提取首字母需要用到pingyin4j.jar,小编在这不提供,大家可以在网上下载
//自定义字母导航控件
public class SlidView extends View {
private String[] strs = {"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 Paint paint;
private OnTouchFirstListener listener;
public SlidView(Context context) {
this(context, null);
}
public SlidView(Context context, AttributeSet attrs) {
this(context, attrs, 0);
}
public SlidView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
paint = new Paint();
paint.setAntiAlias(true);
paint.setColor(Color.GRAY);
paint.setTypeface(Typeface.DEFAULT_BOLD);
}
// px---->sp
protected int sp2px(int spVal) {
return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP, spVal, getResources().getDisplayMetrics());
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
for (int i = 0; i < strs.length; i++) {
paint.setColor(i == index ? Color.RED : Color.BLACK);
paint.setTextSize(i == index ? sp2px(18) : sp2px(16));
int x = (int) (getWidth() - paint.measureText(strs[i])) / 2;
int y = getHeight() / strs.length * (i + 1);
canvas.drawText(strs[i], x, y, paint);
}
}
int index = -1; //获取触摸到字母索引的位置
//触碰事件
//按下,松开,拖动
@Override
public boolean onTouchEvent(MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
case MotionEvent.ACTION_MOVE:
float y = event.getY();
this.setBackgroundColor(Color.GRAY);
//获取触摸到字母的位置
index = (int) y * strs.length / getHeight();
listener.onTouch(strs[index]);
break;
case MotionEvent.ACTION_UP:
this.setBackgroundColor(android.R.color.transparent);
index = -1;
listener.onRelease();
break;
}
//重绘
invalidate();
return true;
}
public void setFirstListener(OnTouchFirstListener listener) {
this.listener = listener;
}
}
/**
* OnTouchFirstListener 接口
* onTouch:触摸到了那个字母
* onRelease:up释放时中间显示的字母需要设置为GONE
*/
public interface OnTouchFirstListener {
void onTouch(String ch);
void onRelease();
}


猜你喜欢
- 本文实例为大家分享了java实现邮箱群发的具体代码,供大家参考,具体内容如下近来无事,在网上看了一些大牛文章,其中看到一篇比较好的,分享给大
- 一、类成员的访问级别public:可由任何代码访问。private(默认):只能由类中的代码访问。internal:只能由它所在的项目(程序
- 本文实例为大家分享了Android ViewPager实现轮播图效果的具体代码,供大家参考,具体内容如下先上一张效果图:说到ViewPage
- mybatisplus支持多种主键生成策略,默认采用认 ID_WORKER 即雪花算法雪花算法snowflflake是Twitter开源的分
- 本文实例讲述了C#利用System.Uri转URL为绝对地址的方法。分享给大家供大家参考。具体分析如下:在使用ASPOSE.Word生成Wo
- 通过子类调用父类的变量,有两种方法:1、把父类的变量设置成public:package triangle.opengl.wlz.stu.ch
- 我们要使用java来操作redis什么是Jedis?什么是Jedis 是Redis官方推荐的java连接开发工具!使用Java操作Redis
- 什么是RESTful APIRESTful API是一种基于HTTP协议的Web API,它的设计原则是简单、可扩展、轻量级、可缓存、可靠、
- 本文实例为大家分享了Java实现登录和注册的具体代码,供大家参考,具体内容如下登录和注册案例的分析:我们在完成一个需求时,需要面向对象,我们
- 谷歌在推出Android5.0的同时推出了一些新控件,Android5.0中最常用的新控件有下面5种。1. CardView(卡片视图)Ca
- 协程属于Kotlin中非常有特色的一项技术,因为大部分编程语言中是没有协程这个概念的。那么什么是协程呢?它其实和线程有点相似,可以简单地将它
- 1. 什么是局部类型?C# 2.0 引入了局部类型的概念。局部类型允许我们将一个类、结构或接口分成几个部分,分别实现在几个不同的.cs文件中
- .net core提供了Json处理模块,在命名空间System.Text.Json中,下面通过顶级语句,对C#的Json功能进行讲解。序列
- settings.xml有什么用?如果在Eclipse中使用过Maven插件,想必会有这个经验:配置settings.xml文件的路径。se
- 题目描述:在数组中的两个数字,如果前面一个数字大于后面的数字,则这两个数字组成一个逆序对。输入一个数组,求出这个数组中的逆序对的总数P。并将
- 最近经朋友介绍开始玩 密传 网络游戏 升级升级,突然觉得太费键盘,于是自己用C#写了一个程序,想代替我的操作,自己去打怪物,自己升级 用这个
- 流行的应用的导航一般分为两种,一种是底部导航,一种是侧边栏。说明IDE:AS,Android studio;模拟器:genymotion;实
- 引言青蛙见了蜈蚣,好奇地问:"蜈蚣大哥,我很好奇,你那么多条腿,走路的时候先迈哪一条啊?"蜈蚣听后说:"青蛙老
- 本文实例为大家分享了C#抽象类与抽象方法的具体实现代码,供大家参考,具体内容如下1.代码class Program { stat
- 用过ios的都知道ios上输入法关闭的同时会自动关闭输入框,那么在android上如何实现监听输入法弹出和关闭呢?本篇文章就为你提供了一种可