自定义view实现联系人界面

效果图



布局

<?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">
    <include layout="@layout/header" />

<RelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent">



    <android.support.v4.widget.SwipeRefreshLayout
        android:id="@+id/vrl_refresh"
        android:layout_width="match_parent"
        android:layout_height="match_parent">





            <ListView

                android:id="@+id/lv"
                android:layout_width="match_parent"
                android:layout_height="match_parent"
                android:divider="@null"
                android:dividerHeight="0dp"

       ></ListView>



    </android.support.v4.widget.SwipeRefreshLayout>
    <com.example.liuan.huanxin.ui.view.MySlideBar
        android:layout_width="30dp"
        android:layout_height="match_parent"
        android:layout_alignParentRight="true" />
    <TextView
        android:visibility="gone"
        android:id="@+id/tv_center"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerInParent="true"
        android:background="@drawable/ease_show_head_toast_bg"
        android:padding="20dp"
        android:textColor="#fff"
        android:text="A"
        android:textAlignment="center"
        android:textSize="40sp" />
</RelativeLayout>


</LinearLayout>

自定义view

package com.example.liuan.huanxin.ui.view;

import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ListView;
import android.widget.TextView;

import com.example.liuan.huanxin.R;
import com.example.liuan.huanxin.ui.adapter.ContactsAdapter;

import java.util.List;

/**
 * Name: MySlideBar
 * Action:
 * Author: liuan
 * creatTime:2017-02-15 09:06
 */

public class MySlideBar extends View {

    private float letterX;
    private String[] letterStr = new String[]{"A",
            "B",
            "C",
            "D",
            "E",
            "F",
            "G",
            "H",
            "I",
            "J",
            "K",
            "L",
            "M",
            "N",
            "O",
            "P",
            "Q",
            "R",
            "S",
            "T",
            "U",
            "V",
            "X",
            "W",
            "Y",
            "Z"

    };
    private float letterHeight;
    private Paint paint;
    private TextView tvcenter;
    private ViewGroup viewGroup;
    private ListView lvContacts;


    public MySlideBar(Context context) {
        super(context, null);
    }

    public MySlideBar(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public MySlideBar(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        paint = new Paint();
        paint.setColor(Color.parseColor("#FF0000"));
        paint.setTextSize(22);
        paint.setTextAlign(Paint.Align.CENTER);
    }


    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        //计算索引字母的x和y坐标
        //x坐标控件宽度的一半
        letterX = getMeasuredWidth() / 2;
        letterHeight = (getMeasuredHeight() + 0f) / letterStr.length;
    }

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

        //drawText起点是左下角
        for (int i = 0; i < letterStr.length; i++) {
            //加1 因为是从左下角开始的
            canvas.drawText(letterStr[i], letterX, letterHeight * (i + 1), paint);
        }

    }

    @Override
    public boolean onTouchEvent(MotionEvent event) {
        //获取自己的父容器 再获取中间文字的控件
        if (viewGroup == null) {
            viewGroup = (ViewGroup) getParent();
            tvcenter = (TextView) viewGroup.findViewById(R.id.tv_center);
            lvContacts = (ListView) viewGroup.findViewById(R.id.lv);
        }

        switch (event.getAction()) {

            case MotionEvent.ACTION_DOWN:
            case MotionEvent.ACTION_MOVE:
                setBackgroundResource(R.drawable.myslidebar_bg);
                //获取当前手指坐标对应的字母
                int index = (int) (event.getY() / letterHeight);

                tvcenter.setVisibility(VISIBLE);
                if(index>=25){
                    index=25 ;

                }
                if(index<=0){
                    index=0;
                }
                String letter = letterStr[index];
                tvcenter.setText(letter);

                //获取ListView中的数据 找到当前首字母对应的条目位置
                //设置lv
                ContactsAdapter adapter = (ContactsAdapter) lvContacts.getAdapter();
                List<String> usernames = adapter.getData();
                for (int i = 0; i < usernames.size(); i++) {
                    if (letterStr[index].equals(usernames.get(i).substring(0, 1).toUpperCase())) {
                        lvContacts.setSelection(i);
                    }
                }


                break;
            case MotionEvent.ACTION_UP:




                setBackgroundResource(android.R.color.transparent);
                tvcenter.setVisibility(GONE);

                break;


        }
        return true;
    }

}

代码实现

package com.example.liuan.huanxin.ui.fragment;

import android.content.Intent;
import android.support.v4.widget.SwipeRefreshLayout;
import android.view.View;
import android.widget.AdapterView;
import android.widget.ImageButton;
import android.widget.ListView;
import android.widget.TextView;

import com.example.liuan.huanxin.R;
import com.example.liuan.huanxin.ui.adapter.ContactsAdapter;
import com.example.liuan.huanxin.ui.activity.AddFrientActivity;
import com.example.liuan.huanxin.utils.ThreadUtil;
import com.hyphenate.chat.EMClient;
import com.hyphenate.exceptions.HyphenateException;

import java.util.ArrayList;
import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * Name: ConversationFragment
 * Action:
 * Author: liuan
 * creatTime:2017-02-14 15:51
 */

public class ContactsFragment extends BaseFragment implements SwipeRefreshLayout.OnRefreshListener, AdapterView.OnItemLongClickListener {
    @Bind(R.id.tv_title)
    TextView tvTitle;
    @Bind(R.id.ib_back)
    ImageButton ibBack;
    @Bind(R.id.ib_add)
    ImageButton ibAdd;
    @Bind(R.id.lv)
    ListView lv;
    @Bind(R.id.vrl_refresh)
    SwipeRefreshLayout srlRefresh;
    @Bind(R.id.tv_center)
    TextView tvCenter;
    private ContactsAdapter contactsAdapter;
    private boolean isRefresh;
    private List<String> data = new ArrayList<>();

    @Override
    protected void initData() {
        tvTitle.setText("联系人");
        ibAdd.setVisibility(View.VISIBLE);
        contactsAdapter = new ContactsAdapter();
        contactsAdapter.setDate(data);
        lv.setAdapter(contactsAdapter);
//监听下拉刷新
        srlRefresh.setOnRefreshListener(this);
        srlRefresh.setColorSchemeResources(R.color.maincolor);
        //从环信服务器获取好友列表
        getContacts();

        lv.setOnItemLongClickListener(this);

    }

    private void getContacts() {
        ThreadUtil.executeSubThread(new Runnable() {

            @Override
            public void run() {
                try {
                    final List<String> userNames = EMClient.getInstance().contactManager().getAllContactsFromServer();
                    ThreadUtil.executeMainThread(new Runnable() {
                        @Override
                        public void run() {
                            data.clear();
                            //展示数据
                            data.addAll(userNames);
                            contactsAdapter.notifyDataSetChanged();
                            if (isRefresh) {
                                srlRefresh.setRefreshing(false);
                                isRefresh = false;
                            }
                        }
                    });


                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });
    }

    @Override
    protected View initView() {
        View view = View.inflate(mActivity, R.layout.fragment_contacts, null);
        ButterKnife.bind(this, view);
        return view;
    }


    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.unbind(this);
    }


    @Override
    public void onRefresh() {
        isRefresh = true;
        getContacts();

    }


    @OnClick({R.id.ib_back, R.id.ib_add})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ib_back:
   ;mActivity.finish();
                break;
            case R.id.ib_add:
                startActivity(new Intent(mActivity,AddFrientActivity.class));
                break;
        }
    }

    @Override
    public boolean onItemLongClick(AdapterView<?> parent, View view, final int position, long id) {
        ThreadUtil.executeSubThread(new Runnable() {
            @Override
            public void run() {
                try {
                    EMClient.getInstance().contactManager().declineInvitation(data.get(position));
                    ThreadUtil.executeMainThread(new Runnable() {
                        @Override
                        public void run() {
                            getContacts();
                        }
                    });
                } catch (HyphenateException e) {
                    e.printStackTrace();
                }
            }
        });
        return false;
    }
}


adapter

package com.example.liuan.huanxin.ui.adapter;

import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.TextView;

import com.example.liuan.huanxin.R;

import java.util.List;

import butterknife.Bind;
import butterknife.ButterKnife;

/**
 * Name: ContactsAdapter
 * Action:
 * Author: liuan
 * creatTime:2017-02-14 16:59
 */
public class ContactsAdapter extends BaseAdapter {
    private List<String> userNames = null;

    public void setDate(List<String> userName) {
        this.userNames = userName;
    }
    public List<String> getData() {
        return userNames;
    }
    @Override
    public int getCount() {
        return userNames.size();
    }

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

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

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolde=null;
        if(convertView==null){
        convertView =View.inflate(parent.getContext(), R.layout.item_contacts, null);
            viewHolde= new ViewHolder(convertView);
            convertView.setTag(viewHolde);

        }else{
            viewHolde= (ViewHolder) convertView.getTag();
        }
        String userName = userNames.get(position);
        String fristLetter = getFristLetter(userName);

        if(position==0){
            viewHolde.tvTitle.setVisibility(View.VISIBLE);
        viewHolde.tvTitle.setText(fristLetter);
        }else{
            //判断首字母和上一个字母的首字母是否相同
            String preFistLetter = getFristLetter(userNames.get(position - 1));
            if(fristLetter.equals(preFistLetter)){
                viewHolde.tvTitle.setVisibility(View.GONE);

            }else{
                viewHolde.tvTitle.setVisibility(View.VISIBLE);
                viewHolde.tvTitle.setText(fristLetter);
            }
        }
        viewHolde.tvUserName.setText(userName);

        return convertView;
    }

    private String getFristLetter(String userName2) {
        return userName2.substring(0,1).toUpperCase();
    }



    static class ViewHolder {
        @Bind(R.id.tv_title)
        TextView tvTitle;
        @Bind(R.id.iv_touxiang)
        ImageView ivTouxiang;
        @Bind(R.id.tv_username)
        TextView tvUserName;

        ViewHolder(View view) {
            ButterKnife.bind(this, view);
        }
    }
}


  • 1
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 打赏
    打赏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包

打赏作者

安果移不动

你的鼓励将是我创作的最大动力

¥1 ¥2 ¥4 ¥6 ¥10 ¥20
扫码支付:¥1
获取中
扫码支付

您的余额不足,请更换扫码支付或充值

打赏作者

实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

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

余额充值