Android好友联系人按字母排序分组,自定义通讯录导航栏View

本文介绍如何在Android应用中模仿微信的联系人列表,通过自定义View实现字母排序分组和通讯录导航栏。内容涵盖自定义View的创建、背景资源设置、颜色配置、mipmap图标、Activity代码、页面布局、实体类User的设计以及适配器的使用,同时讲解了RecyclerView的两种布局方式。
摘要由CSDN通过智能技术生成

Android中仿微信实现联系人列表 按字母排序分组 自定义通讯录导航栏View,下边是效果图:

 

1. 自定义View

public class SideBar extends View {
	// 触摸事件
	private OnTouchingLetterChangedListener onTouchingLetterChangedListener;
	// 26个字母"☆", "#",
	public static String[] b = { "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 int choose = -1;// 选中
	private Paint paint = new Paint();

	private TextView mTextDialog;

	public void setTextView(TextView mTextDialog) {
		this.mTextDialog = mTextDialog;
	}

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

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

	public SideBar(Context context) {
		super(context);
	}

	/**
	 * 重写这个方法
	 */
	protected void onDraw(Canvas canvas) {
		super.onDraw(canvas);
		// 获取焦点改变背景颜色.
		int height = getHeight();// 获取对应高度
		int width = getWidth(); // 获取对应宽度
		int singleHeight = height / b.length;// 获取每一个字母的高度

		for (int i = 0; i < b.length; i++) {
			paint.setColor(getResources().getColor(R.color.black));
			paint.setTypeface(Typeface.DEFAULT);
			paint.setAntiAlias(true);
			paint.setTextSize(24);
			// 选中的状态
			if (i == choose) {
				paint.setColor(getResources().getColor(R.color.yellow));
				paint.setFakeBoldText(true);
			}
			// x坐标等于中间-字符串宽度的一半.
			float xPos = width / 2 - paint.measureText(b[i]) / 2;
			float yPos = singleHeight * i + singleHeight;
			canvas.drawText(b[i], xPos, yPos, paint);
			paint.reset();// 重置画笔
		}

	}

	@SuppressWarnings("deprecation")
	@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() * b.length);// 点击y坐标所占总高度的比例*b数组的长度就等于点击b中的个数.

		switch (action) {
		case MotionEvent.ACTION_UP:
			setBackgroundDrawable(new ColorDrawable(0x00000000));//
			choose = -1;// up 时是否显示选中颜色
			invalidate();
			if (mTextDialog != null) {
				mTextDialog.setVisibility(View.INVISIBLE);
			}
			if (listener != null) {
				listener.noTouchLetter();
			}
			break;
		default:
			setBackgroundResource(R.drawable.sidebar_background);//
			setAlpha((float) 0.7);
			if (oldChoose != c) {
				if (c >= 0 && c < b.length) {
					if (listener != null) {
						listener.onTouchingLetterChanged(b[c]);
					}
					if (mTextDialog != null) {
						mTextDialog.setText(b[c]);
						mTextDialog.setTextColor(Color.WHITE);
						mTextDialog.setVisibility(View.VISIBLE);
					}

					choose = c;
					invalidate();
				}
			}

			break;
		}
		return true;
	}

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

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

}

2. drawable下新建 sidebar_background.xml

<?xml version="1.0" encoding="utf-8"?>
<shape android:shape="rectangle"
  xmlns:android="http://schemas.android.com/apk/res/android">
    <gradient android:startColor="#66000000" android:endColor="#66000000" android:angle="90.0" />
    
    <corners
        android:topLeftRadius="0dip"
        android:bottomLeftRadius="0dip"/>
    
</shape>

3. color

    <color name="black">#000000</color>
    <color name="yellow">#F99503</color>

4. mipmap

    search_goods     

    

    bg_hitchar.png  

    

5.Activity代码

public class FriendSListActivity extends AppCompatActivity implements View.OnClickListener{

    private TextView tvSearchFriend;
    private RecyclerView rvShowNeighbourList;
    private SideBar sideBar;
    private TextView textView;
    private FriendListRvAdapter friendListRvAdapter;
    public static List<User>mDatas = new ArrayList<>();
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_bbb);
        initView();
        setAdapter();
    }

    private void initView() {
        tvSearchFriend=findViewById(R.id.tv_search_friend);
        rvShowNeighbourList = findViewById(R.id.rv_show_neighbour_list);
        textView = findViewById(R.id.tv_show_selete_zm);
        sideBar = findViewById(R.id.side_bar);
        tvSearchFriend.setOnClickListener(this);
    }

    @Override
    public void onClick(View v) {
        switch (v.getId()){
            case R.id.tv_search_friend:
                Intent intent = new Intent(NeighbourListActivity.this,SearchActivity.class);
                startActivity(intent);
                overridePendingTransition(0, 0);
                break;
        }
    }
    
    private void setListener() {
        sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {
            @Override
            public void onTouchingLetterChanged(String s) {
//                sideBar.setTextView(textView);
                textView.setVisibility(View.VISIBLE);
                textView.setText(s);
                for(int i = 0;i<mDatas.size();i++){
                    if(mDatas.get(i).getUserNmaeFirstLetter().equals(s)){
//                        rvShowNeighbourList.scrollToPosition(i);
                        ((LinearLayoutManager)rvShowNeighbourList.getLayoutManager()).scrollToPositionWithOffset(i, 0);
                        return;
                    }
                }
            }
            @Override
            public void noTouchLet
  • 0
    点赞
  • 8
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
要实现通讯录按名字首字母排序分组,可以按照以下步骤进行: 1. 获取通讯录数据,并将每个联系人的名字转换为拼音。 2. 根据拼音首字母联系人进行分组。 3. 对每个分组内的联系人按照名字进行排序。 4. 在页面上渲染每个分组及其对应的联系人。 以下是一个简单的实现示例: 1. 使用 pinyin 库将联系人名字转换为拼音: ```js import pinyin from 'pinyin'; const contacts = [ { name: '张三', phone: '123456789' }, { name: '李四', phone: '987654321' }, // ... ]; const pinyinContacts = contacts.map(contact => { const pinyinName = pinyin(contact.name, { style: pinyin.STYLE_FIRST_LETTER }).join(''); return { ...contact, pinyinName }; }); ``` 2. 根据拼音首字母联系人进行分组: ```js const groupedContacts = pinyinContacts.reduce((groups, contact) => { const firstLetter = contact.pinyinName[0].toUpperCase(); if (!groups[firstLetter]) { groups[firstLetter] = []; } groups[firstLetter].push(contact); return groups; }, {}); ``` 3. 对每个分组内的联系人按照名字进行排序: ```js Object.keys(groupedContacts).forEach(key => { groupedContacts[key].sort((a, b) => a.name.localeCompare(b.name)); }); ``` 4. 在页面上渲染每个分组及其对应的联系人: ```html <template> <div> <div v-for="(contacts, letter) in groupedContacts" :key="letter"> <h2>{{ letter }}</h2> <ul> <li v-for="contact in contacts" :key="contact.phone">{{ contact.name }}</li> </ul> </div> </div> </template> <script> export default { data() { return { groupedContacts: {}, }; }, mounted() { // 获取联系人数据并处理分组排序 // ... this.groupedContacts = groupedContacts; }, }; </script> ```
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值