本文介绍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);
}
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;
}
}
public interface OnTouchFirstListener {
void onTouch(String ch);
void onRelease();
}
您可能感兴趣的文章:Android自定义View实现字母导航栏Android自定义View实现字母导航栏的代码Android使用fragment实现左侧导航Android侧滑导航栏的实例代码Android程序开发之使用Design包实现QQ动画侧滑效果和滑动菜单导航Android程序开发之Fragment实现底部导航栏实例代码Android BottomNavigationBar底部导航控制器使用方法详解Android实现底部导航栏功能(选项卡)Android 开发之BottomBar+ViewPager+Fragment实现炫酷的底部导航效果Android实现Recycleview悬浮粘性头部外加右侧字母导航