通讯录列表

定义taginfo 类


自定义控件  SideBar

public class SidBarView extends View{

    private String[] character = { "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 mPaint = new Paint();

    private TextView mTextView;
    /**
     * 点击到的字符
     */
    private int choose = -1;

    /**
     * 效果:按住控件时,会显现字母
     * @param textView
     */
    public void setTextView(TextView textView){
        mTextView = textView;
    }

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

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

自定义监听

public interface OnselectCharListener{
        void onSelect(String s);
    }

    private OnselectCharListener mOnselectChar;
    public void setOnselectCharListener(OnselectCharListener onselectCharListener){
        mOnselectChar = onselectCharListener;
    }

点击事件

 @Override
    public boolean onTouchEvent(MotionEvent event) {
        /**
         * 获取 Y 方向的点击位置
         */
        float downY = event.getY();

//        当前点的位置 / 总高度 * 字体的高度
        int c = (int) (downY / getHeight() * character.length);
        switch (event.getAction()){

            case MotionEvent.ACTION_UP:
                setBackgroundColor(Color.TRANSPARENT);
                mTextView.setVisibility(GONE);
                choose = -1;
                invalidate();
                break;

            default:
                setBackgroundResource(R.drawable.sidebar_bg);
        /**
         * 按下去
         * 判断c是否在集合长度内
         * 触发绘制
         * 显示效果
         * 文字传入  效果里显示为选中的字母
         */
                if (c >= 0 && c < character.length){
                    choose = c;
                    invalidate();

                    mTextView.setVisibility(VISIBLE);
                    mTextView.setText(character[c]);

                    if (mOnselectChar != null){
                        mOnselectChar.onSelect(character[c]);
                    }
                }
                break;
        }
        return true;        //自己处理
    }

绘制

@Override
    protected void onDraw(Canvas canvas) {
        super.onDraw(canvas);

        int width = getWidth();
        int singleHeight = getHeight() / character.length;     //Y方向为竖直

        for (int i = 0; i < character.length; i++) {
            mPaint.setColor(Color.DKGRAY);
            mPaint.setAntiAlias(true);        //抗锯齿
            mPaint.setTextSize(24);
            /**
             * 当前字母选中时出现的效果
             */
            if (choose == i){
                mPaint.setColor(Color.YELLOW);
                mPaint.setTextScaleX(1.6f);
            }

            int xTo = (int) (getWidth() / 2 - mPaint.measureText(character[i]));
            canvas.drawText(character[i], xTo ,(i + 1)*singleHeight, mPaint);

            mPaint.reset();
        }

    }

listview 内容处理

public class ListViewActivity extends BaseActivity{
    private ListView mLvTag;
    private List<TagInfo> mTagInfos;
    private TextView mTvChar;
    private SidBarView mSidebar;

    @Override
    protected int findId() {
        return R.layout.activity_taglist;
    }

    @Override
    protected void initialView() {
        mLvTag = (ListView) findViewById(R.id.lv_tag);
        mTvChar = (TextView) findViewById(R.id.tv_char);
        mSidebar = (SidBarView) findViewById(R.id.sidebar);

        mSidebar.setTextView(mTvChar);
    }

    @Override
    protected void initialListenner() {
        mSidebar.setOnselectCharListener(new SidBarView.OnselectCharListener() {
            @Override
            public void onSelect(String s) {
                int firstIndex = mTagAdapter.getFirstIndex(s);  //获取 S 所在集合的脚标
                mLvTag.setSelection(firstIndex);         //选中当前位置
            }
        });

    }

    @Override
    protected void initialData() {

        mTagInfoList = getData();
        mTagInfos = new ArrayList<>();
        /**
         * 对集合里面进行排序
         */
        Collections.sort(mTagInfoList, new TitleComparator());

        mTagInfos.addAll(mTagInfoList);
        mTagAdapter = new TagAdapter();

        mLvTag.setAdapter(mTagAdapter);

    }

    private List<TagInfo> mTagInfoList;
    private List<TagInfo> getData(){

        List<TagInfo> tagList = new ArrayList<>();
        /**
         * 将副标题 放入集合
         */
        String[] tagArray = getResources().getStringArray(R.array.listpersons);
        for (int i = 0; i < tagArray.length; i++) {

            String str = tagArray[i];      //数组转化成字符串

            TagInfo tagInfo = new TagInfo();
            tagInfo.setTitle(str);

            String pinyin = PinyinHelper.getShortPinyin(str);
            tagInfo.setTitlePinyin(pinyin);

            int Asic = pinyin.toUpperCase().charAt(0);     //拼音 转化 哈希码值
            if (Asic >= 65 && Asic <= 90){
                tagInfo.setFirstPinyin(pinyin.substring(0,1).toUpperCase());
            }else {
                tagInfo.setFirstPinyin("#");
            }

            tagList.add(tagInfo);
        }

        return tagList;
    }

    @Override
    public void onClick(View v) {

    }

    private TagAdapter mTagAdapter;
    private class TagAdapter extends BaseAdapter{

        @Override
        public int getCount() {
            if (mTagInfos!= null){

                return mTagInfos.size();
            }
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder viewHolder;
            if (convertView == null){
                convertView = View.inflate(ListViewActivity.this,R.layout.item_taglist,null);
                viewHolder = new ViewHolder(convertView);
                convertView.setTag(viewHolder);
            }else {
                viewHolder = (ViewHolder) convertView.getTag();
            }

//            获取数据
            TagInfo tagInfo = mTagInfos.get(position);
        /**
         * 拿到副标题拼音的首字母
         * 获得该首字母在集合中的位置
         */
            int firstIndex = getFirstIndex(tagInfo.getFirstPinyin());
        /**
         * 依据首字母归类好
         * 避免重复
         */
            if (firstIndex == position){
                viewHolder.tvTag.setVisibility(View.VISIBLE);
                viewHolder.tvTag.setText(tagInfo.getFirstPinyin());
            }else {
                viewHolder.tvTag.setVisibility(View.GONE);
            }
            viewHolder.tvDes.setText(tagInfo.getTitle());
            return convertView;
        }

        /**
         * 返回副标题所在集合的脚标
         * @param name
         * @return
         */
        private int getFirstIndex(String name){
            for (int i = 0; i < mTagInfos.size(); i++) {
                if (mTagInfos.get(i).getFirstPinyin().equals(name)){
                    return i;
                }
            }
            return -1;
        }

        class ViewHolder{
            TextView tvTag;
            TextView tvDes;
            public ViewHolder(View itemView){
                tvTag = (TextView) itemView.findViewById(R.id.item_tv_tag);
                tvDes = (TextView) itemView.findViewById(R.id.item_tv_des);
            }
        }

        @Override
        public Object getItem(int position) {
            return null;
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }
    }

    /**
     * 副标题首字母比较
     */
    private class TitleComparator implements Comparator<TagInfo>{

        @Override
        public int compare(TagInfo o1, TagInfo o2) {
            if (o1.getFirstPinyin().charAt(0) < 65 || o1.getFirstPinyin().charAt(0) > 90){
                return 1;
            }else if (o2.getFirstPinyin().charAt(0) < 65 || o2.getFirstPinyin().charAt(0) > 90){
                return -1;
            }
            return o1.getFirstPinyin().compareTo(o2.getFirstPinyin());
        }
    }
}

两个XML

1.
    <ListView
        android:id="@+id/lv_tag"
        android:layout_width="match_parent"
        android:layout_height="match_parent">

    </ListView>

    <TextView
        android:id="@+id/tv_char"
        android:padding="15dp"
        android:visibility="gone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="A"
        android:layout_centerInParent="true"
        android:background="@drawable/pinyin_select_bg"/>

    <android.at.com.matchbox.tag_list.SidBarView
        android:id="@+id/sidebar"
        android:layout_marginBottom="20dp"
        android:layout_centerVertical="true"
        android:layout_marginRight="10dp"
        android:layout_width="25dp"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"/>
2.

<TextView
        android:id="@+id/item_tv_tag"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="A"
        android:textSize="20sp"
        android:padding="5dp"
        android:background="#fdd9a5"/>
    <TextView
        android:id="@+id/item_tv_des"
        android:textSize="15sp"
        android:padding="10dp"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:text="副标题"/>
    <View
        android:layout_width="match_parent"
        android:layout_height="1dp"
        android:background="#a4a4a4"></View>


FIN





以下是一个简单的通讯录列表的OC代码实现: ``` // Contact.h #import <Foundation/Foundation.h> @interface Contact : NSObject @property (nonatomic, copy) NSString *name; @property (nonatomic, copy) NSString *phone; - (instancetype)initWithName:(NSString *)name phone:(NSString *)phone; @end // Contact.m #import "Contact.h" @implementation Contact - (instancetype)initWithName:(NSString *)name phone:(NSString *)phone { self = [super init]; if (self) { self.name = name; self.phone = phone; } return self; } @end // ContactCell.h #import <UIKit/UIKit.h> @interface ContactCell : UITableViewCell @property (nonatomic, strong) UILabel *nameLabel; @property (nonatomic, strong) UILabel *phoneLabel; @end // ContactCell.m #import "ContactCell.h" @implementation ContactCell - (instancetype)initWithStyle:(UITableViewCellStyle)style reuseIdentifier:(NSString *)reuseIdentifier { self = [super initWithStyle:style reuseIdentifier:reuseIdentifier]; if (self) { self.nameLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 10, 200, 20)]; [self.contentView addSubview:self.nameLabel]; self.phoneLabel = [[UILabel alloc] initWithFrame:CGRectMake(15, 35, 200, 20)]; [self.contentView addSubview:self.phoneLabel]; } return self; } @end // ContactListViewController.h #import <UIKit/UIKit.h> @interface ContactListViewController : UITableViewController @end // ContactListViewController.m #import "ContactListViewController.h" #import "Contact.h" #import "ContactCell.h" @interface ContactListViewController () @property (nonatomic, strong) NSMutableArray<Contact *> *contacts; @end @implementation ContactListViewController - (void)viewDidLoad { [super viewDidLoad]; self.navigationItem.title = @"Contacts"; UIBarButtonItem *addButton = [[UIBarButtonItem alloc] initWithBarButtonSystemItem:UIBarButtonSystemItemAdd target:self action:@selector(addContact)]; self.navigationItem.rightBarButtonItem = addButton; self.contacts = [NSMutableArray array]; Contact *contact1 = [[Contact alloc] initWithName:@"John Smith" phone:@"555-1234"]; [self.contacts addObject:contact1]; Contact *contact2 = [[Contact alloc] initWithName:@"Jane Doe" phone:@"555-5678"]; [self.contacts addObject:contact2]; [self.tableView registerClass:[ContactCell class] forCellReuseIdentifier:@"ContactCell"]; } #pragma mark - Table view data source - (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section { return self.contacts.count; } - (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath { ContactCell *cell = [tableView dequeueReusableCellWithIdentifier:@"ContactCell" forIndexPath:indexPath]; Contact *contact = self.contacts[indexPath.row]; cell.nameLabel.text = contact.name; cell.phoneLabel.text = contact.phone; return cell; } #pragma mark - Actions - (void)addContact { UIAlertController *alert = [UIAlertController alertControllerWithTitle:@"Add Contact" message:nil preferredStyle:UIAlertControllerStyleAlert]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.placeholder = @"Name"; }]; [alert addTextFieldWithConfigurationHandler:^(UITextField * _Nonnull textField) { textField.placeholder = @"Phone"; }]; UIAlertAction *addAction = [UIAlertAction actionWithTitle:@"Add" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) { UITextField *nameField = alert.textFields[0]; UITextField *phoneField = alert.textFields[1]; Contact *contact = [[Contact alloc] initWithName:nameField.text phone:phoneField.text]; [self.contacts addObject:contact]; [self.tableView reloadData]; }]; UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"Cancel" style:UIAlertActionStyleCancel handler:nil]; [alert addAction:addAction]; [alert addAction:cancelAction]; [self presentViewController:alert animated:YES completion:nil]; } @end ``` 在这个实现中,我们创建了一个`Contact`类来表示每个联系人,一个`ContactCell`类来自定义通讯录列表中的单元格,一个`ContactListViewController`类来管理通讯录列表。我们使用`NSMutableArray`来存储所有的联系人,并在视图加载时向其中添加了一些示例联系人。 在`ContactListViewController`中,我们实现了`UITableViewDataSource`协议和`UITableViewDelegate`协议中的方法来显示通讯录列表和处理用户添加新联系人的操作。我们还添加了一个`UIBarButtonItem`,当用户点击它时会出现一个`UIAlertController`来允许用户输入新联系人的信息。最后,我们在`viewDidLoad`方法中注册了`ContactCell`类以供表视图使用。 这只是一个简单的例子,你可以根据自己的需要对其进行修改和扩展。
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值