android自定义view仿微信联系人列表

说明:最近碰到一个需求,弄一个类似国家或省份列表,样式参照微信联系人

文件列表:
step1:主界面 加载列表数据~\app\src\main\java\com\example\iosdialogdemo\MainActivity.java
step2:右侧列表数据排序~\app\src\com\example\iosdialogdemo\CountryPinyinComparator.java
step3:适配器~\app\src\main\java\com\example\iosdialogdemo\CountryAdapter.java
step4:地区bean类~\app\src\main\java\com\example\iosdialogdemo\Country.java
step5:自定义控件~\app\src\main\java\com\example\iosdialogdemo\SideBar.java
step6:item布局~\app\src\main\res\layout\item_country.xml
step7:主界面布局ui~\app\src\main\res\layout\activity_main.xml
效果图:
在这里插入图片描述

step1:~\app\src\main\java\com\example\iosdialogdemo\MainActivity.java

package com.example.iosdialogdemo;import android.app.Activity;import android.content.Intent;import android.os.Bundle;import android.view.View;import android.view.WindowManager;import android.widget.AdapterView;import android.widget.Button;import android.widget.ListView;import android.widget.TextView;import java.util.ArrayList;import java.util.Collections;/*** 国家代码* Created by donkor*/
public class MainActivity extends Activity {private SideBar sideBar;private TextView dialog;private ListView sortListView;private CountryAdapter countryAdapter;private Button btnBack;private ArrayList<Country> countryList;/*** 根据拼音来排列ListView里面的数据类*/private CountryPinyinComparator pinyinComparator;@Overrideprotected void onCreate(Bundle savedInstanceState) {// TODO Auto-generated method stubsuper.onCreate(savedInstanceState);getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN, WindowManager.LayoutParams.FLAG_FULLSCREEN);setContentView(R.layout.activity_main);pinyinComparator = new CountryPinyinComparator();sideBar = (SideBar) findViewById(R.id.sidrbar);dialog = (TextView) findViewById(R.id.dialog);sideBar.setTextView(dialog);sortListView = (ListView) findViewById(R.id.country_lvcountry);btnBack = (Button) findViewById(R.id.btnBack);countryList = new ArrayList<>();btnBack.setOnClickListener(new View.OnClickListener() {@Overridepublic void onClick(View v) {MainActivity.this.finish();}});/*public Country(String country, String countryCode, String sortLetters) {** */countryList.add(new Country("美国","1001","A"));countryList.add(new Country("宋国","1001","S"));countryList.add(new Country("赵国","1001","Z"));countryList.add(new Country("扶余国","1001","F"));countryList.add(new Country("夜郎国","1001","Y"));countryList.add(new Country("天启国","1001","T"));countryList.add(new Country("启明国","1001","Q"));countryList.add(new Country("俄国","1001","E"));countryList.add(new Country("英吉利国","1001","Y"));countryList.add(new Country("法兰西国","1001","F"));countryList.add(new Country("西班牙国","1001","X"));countryList.add(new Country("葡萄牙国","1001","P"));countryList.add(new Country("匈牙利国","1001","X"));countryList.add(new Country("塞尔维亚国","1001","S"));countryList.add(new Country("索马里国","1001","S"));countryList.add(new Country("埃及国","1001","A"));countryList.add(new Country("苏丹国","1001","S"));countryList.add(new Country("哈萨克国","1001","H"));countryList.add(new Country("伊朗国","1001","Y"));//        Log.e("asd", "zone.size(): " + zone.size());// 根据a-z进行排序源数据Collections.sort(countryList, pinyinComparator);
//        adapter = new SortAdapter(getActivity(), SourceDateList);countryAdapter = new CountryAdapter(MainActivity.this, countryList);sortListView.setAdapter(countryAdapter);//        设置右侧触摸监听sideBar.setOnTouchingLetterChangedListener(new SideBar.OnTouchingLetterChangedListener() {@Overridepublic void onTouchingLetterChanged(String s) {//该字母首次出现的位置int position = countryAdapter.getPositionForSection(s.charAt(0));if (position != -1) {sortListView.setSelection(position);}}});sortListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {@Overridepublic void onItemClick(AdapterView<?> parent, View view, int position, long id) {Intent mIntent = new Intent(MainActivity.this, MainActivity.class);Bundle b = new Bundle();String country = countryList.get(position).getCountry();String countryCode = countryList.get(position).getCountryCode().replace("+","");b.putString("country", country);b.putString("countryCode", countryCode);mIntent.putExtras(b);MainActivity.this.setResult(1, mIntent);MainActivity.this.finish();}});}}

step2:D:~\app\src\main\java\com\example\iosdialogdemo\CountryPinyinComparator.java

package com.example.iosdialogdemo;import java.util.Comparator;public class CountryPinyinComparator implements Comparator<Country> {public int compare(Country o1, Country o2) {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());}}
}

step3:~\app\src\main\java\com\example\iosdialogdemo\CountryAdapter.java

package com.example.iosdialogdemo;import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.SectionIndexer;
import android.widget.TextView;import java.util.List;public class CountryAdapter extends BaseAdapter implements SectionIndexer {private List<Country> list = null;private Context mContext;public CountryAdapter(Context mContext, List<Country> list) {this.mContext = mContext;this.list = list;}/*** 当ListView数据发生变化时,调用此方法来更新ListView** @param list*/public void updateListView(List<Country> list) {this.list = list;notifyDataSetChanged();}public int getCount() {return this.list.size();}public Object getItem(int position) {return list.get(position);}public long getItemId(int position) {return position;}public View getView(final int position, View view, ViewGroup arg2) {/**得到手机通讯录联系人信息**/ViewHolder viewHolder;Country mContent=list.get(position);if (view == null) {viewHolder = new ViewHolder();view = LayoutInflater.from(mContext).inflate(R.layout.item_country, null);viewHolder.tvTitle = (TextView) view.findViewById(R.id.title);viewHolder.tvLetter = (TextView) view.findViewById(R.id.catalog);viewHolder.number = (TextView) view.findViewById(R.id.number);view.setTag(viewHolder);} else {viewHolder = (ViewHolder) view.getTag();}//根据position获取分类的首字母的Char ascii值int section = getSectionForPosition(position);//如果当前位置等于该分类首字母的Char的位置 ,则认为是第一次出现if (position == getPositionForSection(section)) {viewHolder.tvLetter.setVisibility(View.VISIBLE);viewHolder.tvLetter.setText(mContent.getSortLetters());} else {viewHolder.tvLetter.setVisibility(View.GONE);}viewHolder.tvTitle.setText(this.list.get(position).getCountry());viewHolder.number.setText(this.list.get(position).getCountryCode());return view;}final static class ViewHolder {TextView tvLetter;TextView tvTitle;TextView number;}/*** 根据ListView的当前位置获取分类的首字母的Char ascii值*/public int getSectionForPosition(int position) {return list.get(position).getSortLetters().charAt(0);}/*** 根据分类的首字母的Char ascii值获取其第一次出现该首字母的位置*/public int getPositionForSection(int section) {for (int i = 0; i < getCount(); i++) {String sortStr = list.get(i).getSortLetters();char firstChar = sortStr.toUpperCase().charAt(0);if (firstChar == section) {return i;}}return -1;}@Overridepublic Object[] getSections() {return null;}
}

step4:D:~\app\src\main\java\com\example\iosdialogdemo\Country.java

package com.example.iosdialogdemo;/*** 城市 与城市代码*/
public class Country {private String country;private String countryCode;private String sortLetters;  //显示数据拼音的首字母public Country(String country, String countryCode, String sortLetters) {this.country = country;this.countryCode = countryCode;this.sortLetters = sortLetters;}public Country() {}public String getCountry() {return country;}public void setCountry(String country) {this.country = country;}public String getCountryCode() {return countryCode;}public void setCountryCode(String countryCode) {this.countryCode = countryCode;}public String getSortLetters() {return sortLetters;}public void setSortLetters(String sortLetters) {this.sortLetters = sortLetters;}
}

step5:~\app\src\main\java\com\example\iosdialogdemo\SideBar.java

package com.example.iosdialogdemo;import android.content.Context;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.graphics.Typeface;
import android.graphics.drawable.ColorDrawable;
import android.util.AttributeSet;
import android.util.DisplayMetrics;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;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 SideBar(Context context) {super(context);}public SideBar(Context context, AttributeSet attrs) {super(context, attrs);}public SideBar(Context context, AttributeSet attrs, int defStyleAttr) {super(context, attrs, defStyleAttr);}public void setTextView(TextView mTextDialog) {this.mTextDialog = mTextDialog;}/*** 重写这个方法*/protected void onDraw(Canvas canvas) {super.onDraw(canvas);// 获取焦点改变背景颜色.int height = getHeight();// 获取对应高度int width = getWidth(); // 获取对应宽度int singleHeight = height / b.length;// 获取每一个字母的高度DisplayMetrics dm = new DisplayMetrics();dm = getResources().getDisplayMetrics();int screenWidth = dm.widthPixels;      // 屏幕宽(像素,如:480px)int screenHeight = dm.heightPixels;     // 屏幕高(像素,如:800px)for (int i = 0; i < b.length; i++) {paint.setColor(Color.rgb(11,181,94));paint.setTypeface(Typeface.DEFAULT_BOLD);paint.setAntiAlias(true);if (screenWidth == 720 && screenHeight == 1280) {paint.setTextSize(22);} else if (screenWidth == 1536 && screenHeight == 2560) {paint.setTextSize(50);} else {paint.setTextSize(35);}float xPos = width / 2 - paint.measureText(b[i]) / 2;float yPos = singleHeight * i + singleHeight;// 选中的状态if (i == choose) {paint.setColor(Color.parseColor("#ffffff"));paint.setFakeBoldText(true);Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(),R.mipmap.ic_launcher);canvas.drawBitmap(bitmap, width / 6, singleHeight * i + singleHeight / 5, paint);}// x坐标等于中间-字符串宽度的一半.canvas.drawText(b[i], xPos, yPos, paint);paint.reset();// 重置画笔}}@Overridepublic 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;//invalidate();if (mTextDialog != null) {mTextDialog.setVisibility(View.INVISIBLE);}break;default:
//                setBackgroundResource(R.mipmap.show_toast_bg);if (oldChoose != c) {if (c >= 0 && c < b.length) {if (listener != null) {listener.onTouchingLetterChanged(b[c]);}if (mTextDialog != null) {mTextDialog.setText(b[c]);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);}
}

step6:~\app\src\main\res\layout\item_country.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="match_parent"android:orientation="vertical"><TextViewandroid:id="@+id/catalog"android:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/titleBackground"android:paddingBottom="5dp"android:paddingLeft="15dp"android:paddingTop="5dp"android:text="A"android:textColor="@android:color/black"android:textStyle="bold" /><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="@android:color/white"android:orientation="horizontal"android:paddingLeft="23dp"android:paddingBottom="8dp"android:paddingRight="8dp"android:paddingTop="8dp"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:layout_marginLeft="25dp"android:orientation="horizontal"android:paddingBottom="10dp"android:paddingTop="10dp"><TextViewandroid:id="@+id/title"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_vertical"android:gravity="center_vertical"android:text="hhhh"android:textColor="@android:color/black"android:textSize="16sp" /><TextViewandroid:id="@+id/number"android:layout_width="wrap_content"android:layout_height="wrap_content"android:layout_gravity="center_vertical"android:gravity="center_vertical"android:text="hhhh"android:layout_marginLeft="10dp"android:textColor="@android:color/black"android:textSize="12sp" /></LinearLayout></LinearLayout></LinearLayout>

step7:~\app\src\main\res\layout\activity_main.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="match_parent"android:background="@color/background"android:orientation="vertical"><LinearLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"android:background="@color/titleBackground"android:orientation="horizontal"android:weightSum="3"><LinearLayoutandroid:layout_width="0dp"android:layout_height="match_parent"android:layout_weight="1"android:orientation="horizontal"><Buttonandroid:id="@+id/btnBack"android:layout_width="wrap_content"android:layout_height="wrap_content"android:background="@null"android:drawablePadding="10dp"android:gravity="center|left"android:paddingLeft="10dp"android:text="返回"android:textAllCaps="false"android:textSize="15sp" /></LinearLayout><TextViewandroid:layout_width="0dp"android:layout_height="match_parent"android:layout_centerInParent="true"android:layout_weight="1"android:gravity="center"android:text="国家"android:textColor="@android:color/black"android:textSize="15sp"android:textStyle="bold" /></LinearLayout><Viewandroid:layout_width="match_parent"android:layout_height="0.3dp"android:background="@android:color/darker_gray" /><FrameLayoutandroid:layout_width="match_parent"android:layout_height="wrap_content"><ListViewandroid:id="@+id/country_lvcountry"android:layout_width="match_parent"android:layout_height="match_parent"android:layout_gravity="center"android:scrollbars="none"android:divider="@null"android:fastScrollEnabled="true" /><TextViewandroid:id="@+id/dialog"android:layout_width="80dp"android:layout_height="80dp"android:layout_gravity="center"android:background="@mipmap/ic_launcher"android:gravity="center"android:textColor="#ffffffff"android:textSize="30sp"android:visibility="invisible" /><com.example.iosdialogdemo.SideBarandroid:id="@+id/sidrbar"android:layout_width="33dp"android:layout_height="match_parent"android:layout_gravity="right|center" /></FrameLayout></LinearLayout>

end

本文来自互联网用户投稿,该文观点仅代表作者本人,不代表本站立场。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如若转载,请注明出处:http://www.hqwc.cn/news/701048.html

如若内容造成侵权/违法违规/事实不符,请联系编程知识网进行投诉反馈email:809451989@qq.com,一经查实,立即删除!

相关文章

Python 3 中zip()函数的用法

1 创作灵感 我们在阅读代码的时候&#xff0c;经常会看到zip函数&#xff0c;有的时候还和循环在一起用&#xff0c;今天举几个例子测试一下该函数的用法 2.应用举例 &#xff08;1&#xff09;定义了两个列表一个是num,一个是letter (2)使用zip可以把num列表和letter列表中…

计算机vcruntime140.dll找不到如何修复,分享5种靠谱的修复教程

当您在运行某个应用程序或游戏时遇到提示“找不到vcruntime140.dll”&#xff0c;这通常意味着系统中缺少了Visual C Redistributable for Visual Studio 2015或更高版本的一个重要组件。这个错误通常发生在运行某些程序时&#xff0c;系统无法找到所需的动态链接库文件。小编将…

element-ui的表单中,输入框、级联选择器的长度设置

使用<el-col>控制输入框的长度 <el-form-item label"姓名" label-width"80px"><el-col :span"15"><el-input v-model"form.name" autocomplete"off"></el-input></el-col></el-form…

Sectigo SSL证书申请的流程是怎样的?

在当今数字化时代&#xff0c;网络安全成为了一个不可忽视的问题。为了保护网站和用户数据的安全&#xff0c;SSL证书成为了网站运营的重要组成部分。Sectigo作为全球领先的数字证书颁发机构之一&#xff0c;提供了一系列的证书解决方案来满足不同类型网站的需求。以下是对Sect…

【LeetCode刷题】136.只出现一次的数字(Ⅰ)

【LeetCode刷题】136.只出现一次的数字&#xff08;Ⅰ&#xff09; 1. 题目&#xff1a;2.思路分析&#xff1a;思路1&#xff1a;一眼异或&#xff01; 1. 题目&#xff1a; 2.思路分析&#xff1a; 思路1&#xff1a;一眼异或&#xff01; 看到题目&#xff0c;如果有一定基…

Spring Boot 整合讯飞星火3.5通过接口Api接口实现聊天功能(首发)复制粘贴即可使用,后续更新WebSocket实现聊天功能

程序员必备网站&#xff1a; 天梦星服务平台 (tmxkj.top)https://tmxkj.top/#/ 1.pom.xml <dependency><groupId>com.alibaba</groupId><artifactId>fastjson</artifactId><version>1.2.72</version></dependency><depen…

618速递丨各平台内卷严重,这些行业能否率先炸场?

根据最新发布的《中国网络视听发展研究报告&#xff08;2024&#xff09;》显示&#xff0c;71.2%的受访用户因为看短视频和直播进行网上购物&#xff0c;超40%的用户认为短视频和直播是他们的主要消费渠道&#xff0c;内容消费正成为各大电商争夺的关键赛道。 今年618&#x…

pytest中@pytest.mark.parametrize和自定义装饰器如何一起使用?

在Pytest中&#xff0c;pytest.mark.parametrize装饰器用于将测试函数参数化。它允许我们通过传递多个参数和对应的值来运行相同的测试函数多次。另一方面&#xff0c;自定义装饰器可以用于添加额外的功能或重用代码。在本文中&#xff0c;我们将详细介绍如何在Pytest中同时使用…

搜索引擎的设计与实现(四)

目录 6 系统测试 6.1测试重要性 6.2测试用例 结 论 参 考 文 献 前面内容请移步 搜索引擎的设计与实现&#xff08;三&#xff09; 免费源代码&毕业设计论文 搜索引擎的设计与实现 6 系统测试 6.1测试重要性 该项目是在本地服务器上进行运行和调试&#xff0c;…

Go微服务: Gin框架搭建网关, 接入熔断器,链路追踪以及服务端接入限流和链路追踪

概述 本文使用最简单和快速的方式基于Gin框架搭建一个微服务的网关调用微服务的场景网关作为客户端基于RPC调用某一服务端的服务并接入熔断和限流以及链路追踪具体场景&#xff1a;通过网关API查询购物车里的数据在最后&#xff0c;会贴上网关和购物车服务的代码仓库 服务端搭…

Vue接收后端POST、GET返回的zip文件流打开报异常

近期接到一个小任务是将内容导出为 Zip 文件流的行式给前端 Vue 供用户下载&#xff1b;过程中发现一个问题打开 zip 文件报异常&#xff0c;如下&#xff1a; 首先后端这块单独在服务端请求是落盘的文件是正常的&#xff1b;因此后端的这块的逻辑没有问题&#xff1b;但中间前…

VRRP协议-负载分担配置【分别在路由器与交换机上配置】

VRRP在路由器与交换机上的不同配置 一、使用路由器实现负载分担二、使用交换机实现负载分担一、使用路由器实现负载分担 使用R1与R2两台设备分别进行VRRP备份组 VRRP备份组1,虚拟pc1的网关地址10.1.1.254 VRRP备份组2,虚拟pc2的网关地址10.1.1.253 ①备份组1的vrid=1,vrip=…