The @Function of Imitating Wechat and QQ

Keywords: Android Java

The @Function of Imitating Wechat and QQ

Foreword: Some time ago, the company had a project to add @ function, I did not have any idea at that time, and then go online to see if any predecessors have written similar articles or codes. And then I'm here. http://download.csdn.net/detail/u011818090/8534377 Finding the @ function written by someone else, I feel OK, but it's different from my needs, so I adapted his code according to my needs. Now let's talk about my @ function.
First of all, requirements: the central idea of company project requirements is that when you chat in a group, @someone in the group, who receives @ information, will have a red alert in the conversation list, and others receive information as a common message. That's the problem I had at the time, how to get people @ to receive red alerts. There was also a very uncomfortable data document (in the format shown below) which had two schemes: first, tagging by name; and second, tagging by name and user ID. Then we will analyze the following: the first scheme, the name has no uniqueness. So the first one is excluded (the process of excluding is painful, which has experienced many difficult ideas and attempts, because of this wonderful document data format); the second one is that the ID has uniqueness and can also fill in the ID of the document. It can also judge whether the content field contains @ information or a common @ text information. But how to achieve it?

Everyone has used the Wechat facial expression, which corresponds to a specific string. I wonder why this is not possible. A name contains the name and Id. The main idea is to use a regular way to replace a particular format of string with a picture. The code below.

 //Set @Picture and Text Blending
    public static CharSequence getExpressionString(Context context, String srcText,DynamicDrawableSpan drawableSpan){
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(srcText);  //srcText is a stitched string
        String text = builder.toString();
        Pattern pattern = Pattern.compile("\\[2f(.*?)\\]"); //This is an agreed regular string
        Matcher matcher = pattern.matcher(text);
        String atStr,atIndex;
        SpannableString spannable;

        int index = 0;
        while(matcher.find()){
            atIndex = matcher.group(1);//Find matching strings in parentheses () in regular expressions
            atStr = "[2f" + atIndex + "]";
            index = matcher.start(1) - 3; //Get the starting coordinates of matches in parentheses
            spannable = new SpannableString(atStr);
            spannable.setSpan(drawableSpan, 0, spannable.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.replace(index, index + atStr.length(), spannable);
        }
        return builder;
    }

The above method is to replace a drawableSpan spliced into a specific string with a name image regularly.
Here's the code created by spelling name and Id into specific characters

/**
     * Stitching @ and Name
     * @param userName
     * @param userId
     */
    private void spilecName(String userName, String userId) {

        int currentIndex = editText.getSelectionStart();  //Get the starting position of the cursor
        String nameStr = "[2f" + userName + "/" + userId + "]";
        //Delete the previous one by entering the @ symbol into the list of friends and returning the @ person.@
        editText.getText().replace(currentIndex - 1,currentIndex,"");

        setAtImageSpan(nameStr,userName);
    }

You can see that I splice name and Id into String nameStr = 2F + userName + "/" + userId + "]; this form is then matched with regular expressions using pattern = pattern. compile ("\ 2F (*?)\". Here's how to turn text information into picture information

/**
     * Convert @ information into pictures
     * @param nameStr
     * @param name
     */
    private void setAtImageSpan(String nameStr, String name) {
        Editable eidit_text = editText.getEditableText();
        if (null != name){
            String name1 = "@" + name + " ";  //Add a space after it to separate it from the subsequent spliced text.
            if (null != name1 && name1.trim().length() > 0){
                final Bitmap bmp = getNameBitmap(name1);

                DynamicDrawableSpan drawableSpan = new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) {
                    @Override
                    public Drawable getDrawable() {
                        BitmapDrawable drawable = new BitmapDrawable(getResources(),bmp);
                        drawable.setBounds(0,0,
                                            bmp.getWidth(),
                                            bmp.getHeight());
                        return drawable;
                    }
                };

                CharSequence cs = getExpressionString(AtActivity.this, nameStr, drawableSpan);
                builder = new SpannableStringBuilder(cs);

                //Get the location of the cursor
                currentIndex = editText.getSelectionStart();
                builder.setSpan(builder,0, builder.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if (currentIndex < 0 || currentIndex >= eidit_text.length()) {
            eidit_text.append(builder);
        } else {
            eidit_text.insert(currentIndex, builder);
        }
    }

    /**
     * Convert text into pictures
     * @param name
     * @return
     */
    private Bitmap getNameBitmap(String name) {
        Paint paint = new Paint();
        paint.setColor(getResources().getColor(R.color.black));
        paint.setAntiAlias(true);
        paint.setTextSize(DensityUtils.dp2px(AtActivity.this,18));
        Rect rect = new Rect();
        paint.getTextBounds(name,0,name.length(),rect);

        //Get the length of the string on the screen
        int width = (int) (paint.measureText(name));
        final Bitmap bmp = Bitmap.createBitmap(width,rect.height() + 8, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();

        //(Line Height - Font Height) / 2 + Font Height - 6
        float fontTotalHeight = fontMetrics.bottom - fontMetrics.top;
        //  canvas.drawText(name, rect.left, rect.height() - rect.bottom, paint);
        float offY = fontTotalHeight / 2;

        float newY = rect.height() / 2 + offY;
        canvas.drawText(name, rect.left, newY - 4, paint);
        return bmp;
    }

With the above processing, the name and ID information can be stored in a @ picture. By parsing the content of @ information, the receiver determines whether the content has its own Id, and then the system processes it accordingly.

The general idea is finished, some simple logic, you can see the code of the link I gave above. Or look at the whole code attached below. My code also adds the search function of group members'names, the search keyword red processing. Attached is the code as follows:

Note: The code simply writes the sender's @ function information, and does not have the actual chat function (chat is more complex). If you have the @ function needed to do instant chat, I hope this idea can be helpful to you all.
AtActivity code:

package com.example.hhly_pc.enumuse;

import android.content.Context;
import android.content.Intent;
import android.graphics.Bitmap;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.graphics.Rect;
import android.graphics.drawable.BitmapDrawable;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.support.v4.graphics.BitmapCompat;
import android.support.v7.app.AppCompatActivity;
import android.text.Editable;
import android.text.InputFilter;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.DynamicDrawableSpan;
import android.widget.EditText;
import android.widget.Toast;

import com.example.hhly_pc.enumuse.adapter.AppMannager;

import java.util.regex.Matcher;
import java.util.regex.Pattern;

/**
 * Created by hhly-pc on 2017/1/21.
 */
public class AtActivity extends AppCompatActivity {

    private static int a = 0;
    private EditText editText;
    private int currentIndex;
    private SpannableStringBuilder builder;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_at);

        editText = (EditText) findViewById(R.id.et_at);

        //Text Screening in Text Editing Box
        editText.setFilters(new InputFilter[]{new MyInputFilter()});


    }

    private class MyInputFilter implements InputFilter{
        @Override
        public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart, int dend) {
           if (source.toString().equalsIgnoreCase("@") || source.toString().equalsIgnoreCase("@")){
               goAt();
           }
            return source;
        }
    }

    //Match to the @ character and enter the user selection interface
    private void goAt() {
        startActivityForResult(new Intent(this,PersionListActivity.class),100);
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 100 && resultCode == 200){
            String userId = data.getStringExtra("userId");
            String userName = data.getStringExtra("userName");
            System.out.println("userName111    "  + userName + "  userId  " + userId);
            spilecName(userName,userId);
        }
    }


    /**
     * Stitching @ and Name
     * @param userName
     * @param userId
     */
    private void spilecName(String userName, String userId) {

        int currentIndex = editText.getSelectionStart();  //Get the starting position of the cursor
        String nameStr = "[2f" + userName + "/" + userId + "]";
        //Delete the previous one by entering the @ symbol into the list of friends and returning the @ person.@
        editText.getText().replace(currentIndex - 1,currentIndex,"");

        setAtImageSpan(nameStr,userName);
    }

    /**
     * Convert @ information into pictures
     * @param nameStr
     * @param name
     */
    private void setAtImageSpan(String nameStr, String name) {
        Editable eidit_text = editText.getEditableText();
        if (null != name){
            String name1 = "@" + name + " ";  //Add a space after it to separate it from the subsequent spliced text.
            if (null != name1 && name1.trim().length() > 0){
                final Bitmap bmp = getNameBitmap(name1);

                DynamicDrawableSpan drawableSpan = new DynamicDrawableSpan(DynamicDrawableSpan.ALIGN_BASELINE) {
                    @Override
                    public Drawable getDrawable() {
                        BitmapDrawable drawable = new BitmapDrawable(getResources(),bmp);
                        drawable.setBounds(0,0,
                                            bmp.getWidth(),
                                            bmp.getHeight());
                        return drawable;
                    }
                };

                CharSequence cs = getExpressionString(AtActivity.this, nameStr, drawableSpan);
                builder = new SpannableStringBuilder(cs);

                //Get the location of the cursor
                currentIndex = editText.getSelectionStart();
                builder.setSpan(builder,0, builder.length(),Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }

        if (currentIndex < 0 || currentIndex >= eidit_text.length()) {
            eidit_text.append(builder);
        } else {
            eidit_text.insert(currentIndex, builder);
        }
    }

    /**
     * Convert text into pictures
     * @param name
     * @return
     */
    private Bitmap getNameBitmap(String name) {
        Paint paint = new Paint();
        paint.setColor(getResources().getColor(R.color.black));
        paint.setAntiAlias(true);
        paint.setTextSize(DensityUtils.dp2px(AtActivity.this,18));
        Rect rect = new Rect();
        paint.getTextBounds(name,0,name.length(),rect);

        //Get the length of the string on the screen
        int width = (int) (paint.measureText(name));
        final Bitmap bmp = Bitmap.createBitmap(width,rect.height() + 8, Bitmap.Config.ARGB_8888);
        Canvas canvas = new Canvas(bmp);
        Paint.FontMetricsInt fontMetrics = paint.getFontMetricsInt();

        //(Line Height - Font Height) / 2 + Font Height - 6
        float fontTotalHeight = fontMetrics.bottom - fontMetrics.top;
        //  canvas.drawText(name, rect.left, rect.height() - rect.bottom, paint);
        float offY = fontTotalHeight / 2;

        float newY = rect.height() / 2 + offY;
        canvas.drawText(name, rect.left, newY - 4, paint);
        return bmp;
    }

    //Set @Picture and Text Blending
    public static CharSequence getExpressionString(Context context, String srcText,DynamicDrawableSpan drawableSpan){
        SpannableStringBuilder builder = new SpannableStringBuilder();
        builder.append(srcText);
        String text = builder.toString();
        Pattern pattern = Pattern.compile("\\[2f(.*?)\\]");
        Matcher matcher = pattern.matcher(text);
        String atStr,atIndex;
        SpannableString spannable;

        int index = 0;
        while(matcher.find()){
            atIndex = matcher.group(1);
            atStr = "[2f" + atIndex + "]";
            index = matcher.start(1) - 3;
            spannable = new SpannableString(atStr);
            spannable.setSpan(drawableSpan, 0, spannable.length(), Spannable.SPAN_INCLUSIVE_EXCLUSIVE);
            builder.replace(index, index + atStr.length(), spannable);
        }
        return builder;
    }

}

Code PersionListActivity for Group Selection Interface

package com.example.hhly_pc.enumuse;

import android.app.Activity;
import android.app.LoaderManager;
import android.content.Context;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.os.Message;
import android.os.SystemClock;
import android.support.v7.app.AppCompatActivity;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.View;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;
import android.widget.Toast;

import com.example.hhly_pc.enumuse.adapter.BaseRecyclerViewAdapter2;
import com.example.hhly_pc.enumuse.adapter.DividerItemDecoration2;
import com.example.hhly_pc.enumuse.adapter.TestAdapter;

import java.lang.ref.WeakReference;
import java.util.ArrayList;
import java.util.List;

/**
 * Created by hhly-pc on 2017/1/21.
 */
public class PersionListActivity extends AppCompatActivity implements View.OnClickListener{

    private RecyclerView recyclerView;
    private ImageView ivBack;
    private ImageView ivSearch;
    private TextView tv1;
    private static List<Persion> datas;
    private EditText editextSeach;
    private static final int LIST = 0x213;

    private MyHandler myHandler = new MyHandler(PersionListActivity.this);
    //LoaderManager
    /*private Handler mHandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case LIST:

                    SearchContactInfo searchContactInfo = (SearchContactInfo) msg.obj;
                    final List<Persion> persions = searchContactInfo.getAllConctDetailedInfo();
                    adapter = new TestAdapter(persions,PersionListActivity.this);
                    adapter.setSearchContent(searchContactInfo.getSearchName());
                    recyclerView.setAdapter(adapter);
                    adapter.notifyDataSetChanged();

                    adapter.setOnRecyclerViewItemClickListener(new BaseRecyclerViewAdapter2.OnRecyclerViewItemClickListener2() {
                        @Override
                        public void onItemClick(View view, int position) {
                            Intent intent = new Intent();
                            String usetName = datas.get(position).getUsetName();
                            String userId = datas.get(position).getUserId();
                            intent.putExtra("usetName",usetName);
                            intent.putExtra("userId",userId);
                            setResult(200,intent);
                            finish();
                        }
                    });

            }
        }
    };*/
    private TestAdapter adapter;


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
        ivBack = (ImageView) findViewById(R.id.iv_back);
        ivSearch = (ImageView) findViewById(R.id.iv_search);
        tv1 = (TextView) findViewById(R.id.tv_1);
        editextSeach = (EditText) findViewById(R.id.editext_seach);
        ivBack.setOnClickListener(this);
        ivSearch.setOnClickListener(this);
        intData();
        LinearLayoutManager layoutManager = new LinearLayoutManager(this);

        recyclerView.setLayoutManager(layoutManager);
        recyclerView.addItemDecoration(new DividerItemDecoration2(this, LinearLayoutManager.VERTICAL, 1, getResources().getColor(R.color.color_itemMess_divider)));//Setting the partition line of item
        adapter = new TestAdapter(datas,PersionListActivity.this);
        recyclerView.setAdapter(adapter);
        adapter.setOnRecyclerViewItemClickListener(new BaseRecyclerViewAdapter2.OnRecyclerViewItemClickListener2() {
            @Override
            public void onItemClick(View view, int position) {
                Intent intent = new Intent();
                String usetName = datas.get(position).getUsetName();
                String userId = datas.get(position).getUserId();
                intent.putExtra("userName",usetName);
                intent.putExtra("userId",userId);
                setResult(200,intent);
                finish();
            }
        });

        editextSeach.addTextChangedListener(watcher);
    }

    //In order to prevent memory leaks caused by Handler, it is recommended to modify the following writing with static, without holding references to external classes.
    private static class MyHandler extends Handler{
        private WeakReference<PersionListActivity> weakReferenceActivity;

        public MyHandler(Context context){
            PersionListActivity persionListActivity = (PersionListActivity) context;
            weakReferenceActivity = new WeakReference<PersionListActivity>(persionListActivity);
        }

        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            final PersionListActivity weakPersionListActivity2 = weakReferenceActivity.get();
            if (weakPersionListActivity2 != null){ //If the virtual reference is empty, do not operate, or else operate
                switch (msg.what) {
                    case LIST:
                        SearchContactInfo searchContactInfo = (SearchContactInfo) msg.obj;
                        final List<Persion> persions = searchContactInfo.getAllConctDetailedInfo();
                        TestAdapter adapter = new TestAdapter(persions,weakPersionListActivity2);
                        adapter.setSearchContent(searchContactInfo.getSearchName());
                        weakPersionListActivity2.recyclerView.setAdapter(adapter);
                        adapter.notifyDataSetChanged();

                        adapter.setOnRecyclerViewItemClickListener(new BaseRecyclerViewAdapter2.OnRecyclerViewItemClickListener2() {
                            @Override
                            public void onItemClick(View view, int position) {
                                Intent intent = new Intent();
                                String usetName = datas.get(position).getUsetName();
                                String userId = datas.get(position).getUserId();

                                intent.putExtra("userName",usetName);
                                intent.putExtra("userId",userId);
                                weakPersionListActivity2.setResult(200,intent);
                                weakPersionListActivity2.finish();
                            }
                        });

                }

            }
        }
    }

    //Initialization data
    private void intData() {
        datas = new ArrayList<>();
        for (int i = 0; i < 25; i++) {
            datas.add(new Persion("Zhang San" + i,"12345" + i));
        }
    }

    @Override
    public void onClick(View v) {
        int id = v.getId();
        switch(id){
            case R.id.iv_back:
                onBackPressed();
                break;
            case R.id.iv_search:
                tv1.setVisibility(View.GONE);
                ivSearch.setVisibility(View.GONE);
                editextSeach.setVisibility(View.VISIBLE);
                editextSeach.requestFocus();
                InputMethodManager inputMethodManager = (InputMethodManager) editextSeach.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputMethodManager.showSoftInput(editextSeach,0);
                break;
        }
    }

    private TextWatcher watcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {

        }

        @Override
        public void afterTextChanged(Editable s) {
            List<Persion> persions = searchUserNames(datas, s.toString());
            SearchContactInfo searchContactInfo = new SearchContactInfo();
            searchContactInfo.setAllConctDetailedInfo(persions);
            searchContactInfo.setSearchName(s.toString());
            Message msg = new Message();
            msg.what = LIST;
            msg.obj = searchContactInfo;
            myHandler.sendMessage(msg);
        }
    };

    public List<Persion> searchUserNames(List<Persion> data,String name){
        ArrayList<Persion> atName = new ArrayList<>();
        if (data != null && data.size() != 0){
            for (Persion persion : data){
                if (persion.getUsetName().contains(name)){
                    atName.add(persion);
                }
            }
        }

        if (null != atName){
            return atName;
        }

        return null;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        myHandler.removeCallbacksAndMessages(null);
    }
}

There is also a very hanging adapter code BaseRecyclerViewAdapter2 for recyclerView

package com.example.hhly_pc.enumuse.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import com.example.hhly_pc.enumuse.BaseViewHolder;

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

/**
 * Created by hhly-pc on 2017/1/18.
 */
public abstract class BaseRecyclerViewAdapter2<T> extends RecyclerView.Adapter<BaseViewHolder2>{
    private List<T> mData;  //Preparation data
    private Context mContext;
    private int mLayoutResId; //Id of Page Layout
    private LayoutInflater mLayoutInflate;


    //Initialize the Click Listener Interface
    private OnRecyclerViewItemClickListener2 mOnRecyclerViewItemClickListener;
    private onRecyclerViewItemLongClickListener2 mOnRecyclerViewItemLongClickListener2;
    //Constructor
    public BaseRecyclerViewAdapter2(List<T> mData, Context mContext, int mLayoutResId) {  //There are many empty judgments for mData and mLayoutResId.
        this.mData = mData == null ? new ArrayList<T>() : new ArrayList<T>(mData);
        this.mContext = mContext;
        if (0 != mLayoutResId){
            this.mLayoutResId = mLayoutResId;
        }
        this.mLayoutInflate = LayoutInflater.from(mContext);
    }

    @Override
    public void onBindViewHolder(BaseViewHolder2 holder, int position) {
       conver(holder,mData.get(position));
    }

    @Override
    public BaseViewHolder2 onCreateViewHolder(ViewGroup parent, int viewType) {
        BaseViewHolder2 baseViewHolder2 = new BaseViewHolder2(mContext,mLayoutInflate.inflate(mLayoutResId,parent,false));
        initItemClickListener(baseViewHolder2);
        return baseViewHolder2;
    }

    //Initialize click events
    private void initItemClickListener(final BaseViewHolder2 holder2) {
        if (mOnRecyclerViewItemClickListener != null){
            holder2.itemView.setOnClickListener(new View.OnClickListener(){
                @Override
                public void onClick(View v) {
                    mOnRecyclerViewItemClickListener.onItemClick(v,holder2.getLayoutPosition());
                }
            });
        }

        if (mOnRecyclerViewItemLongClickListener2 != null){
            holder2.itemView.setOnLongClickListener(new View.OnLongClickListener(){
                @Override
                public boolean onLongClick(View v) {
                    return mOnRecyclerViewItemLongClickListener2.onItemLongClick(v,holder2.getLayoutPosition());
                }
            });
        }
    }

    @Override
    public int getItemCount() {
        return mData.size();
    }

    public void add(int position,T item){
        mData.add(position,item);
        notifyItemInserted(position);
    }
    //Setting Click Events
    public interface OnRecyclerViewItemClickListener2{
        void onItemClick(View view, int position);
    }

    public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener2 onRecyclerViewItemClickListener2){
        this.mOnRecyclerViewItemClickListener = onRecyclerViewItemClickListener2;
    }

    public interface onRecyclerViewItemLongClickListener2{
        public boolean onItemLongClick(View view,int position);
    }

    public void setOnRecyclerViewItemLongClickListener2(onRecyclerViewItemLongClickListener2 onRecyclerViewItemLongClickListener2){
        this.mOnRecyclerViewItemLongClickListener2 = onRecyclerViewItemLongClickListener2;
    }

    protected abstract void conver(BaseViewHolder2 holder,T item);
}

The implementation class of this adapter, TestAdapter

package com.example.hhly_pc.enumuse.adapter;

import android.content.Context;
import android.graphics.Color;
import android.text.SpannableString;
import android.text.SpannableStringBuilder;
import android.text.TextUtils;
import android.text.style.ForegroundColorSpan;

import com.example.hhly_pc.enumuse.Persion;
import com.example.hhly_pc.enumuse.R;

import java.util.List;

/**
 * Created by hhly-pc on 2017/1/18.
 */
public class TestAdapter extends BaseRecyclerViewAdapter2<Persion> {

    private String mSearchContent;
    public TestAdapter(List<Persion> data,Context context){
        super(data,context, R.layout.list_item);
    }

    @Override
    protected void conver(BaseViewHolder2 holder, Persion item) {
        int start = getColorString(item.getUsetName(), mSearchContent);
        if (start > -1){
            System.out.println("start     " + start);
            SpannableStringBuilder builder = new SpannableStringBuilder(item.getUsetName());
            ForegroundColorSpan redSpan = new ForegroundColorSpan(Color.RED);
            builder.setSpan(redSpan,start,start + mSearchContent.length(), SpannableString.SPAN_EXCLUSIVE_EXCLUSIVE);
            holder.setText(R.id.tv_1,builder);
        }else {
            holder.setText(R.id.tv_1,item.getUsetName());
        }
    }

    public int getColorString(String userName,String mSearchContent){
        int start = -1;
        if (!TextUtils.isEmpty(userName) && !TextUtils.isEmpty(mSearchContent)) {

            if (userName.contains(mSearchContent)) {

                start = userName.indexOf(mSearchContent);

            }
        }
        return start;
    }

    public void setSearchContent(String searchContent){
        this.mSearchContent = searchContent;
    }
}
package com.example.hhly_pc.enumuse.adapter;

import android.content.Context;
import android.support.v7.widget.RecyclerView;
import android.util.SparseArray;
import android.view.View;
import android.widget.TextView;

/**
 * Created by hhly-pc on 2017/1/18.
 */
public class BaseViewHolder2 extends RecyclerView.ViewHolder{
    private Context mContext;
    private final SparseArray<View> views;
    public View converView;

    public BaseViewHolder2(Context countext,View itemView) {
        super(itemView);
        this.mContext = countext;
        this.views = new SparseArray<>();
        converView = itemView;
    }

    public void setText(int viewId,CharSequence s){
        TextView view = getView(viewId);
        view.setText(s);
    }

    public <T extends View> T getView(int viewId){
        View view = views.get(viewId);
        if (view == null){
            view = converView.findViewById(viewId);
            views.put(viewId,view);
        }
        return (T)view;
    }
}
package com.example.hhly_pc.enumuse;

import android.content.Context;
import android.util.TypedValue;

/**
 * Auxiliary Classes of Common Unit Conversion
 */
public class DensityUtils {
    private DensityUtils() {
        /* cannot be instantiated */
        throw new UnsupportedOperationException("cannot be instantiated");
    }

    /**
     * dp Turn px
     *
     * @param context
     * @param
     * @return
     */
    public static int dp2px(Context context, float dpVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP,
                dpVal, context.getResources().getDisplayMetrics());
    }

    /**
     * sp Turn px
     *
     * @param context
     * @param
     * @return
     */
    public static int sp2px(Context context, float spVal) {
        return (int) TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_SP,
                spVal, context.getResources().getDisplayMetrics());
    }

    /**
     * px Turn dp
     *
     * @param context
     * @param pxVal
     * @return
     */
    public static float px2dp(Context context, float pxVal) {
        final float scale = context.getResources().getDisplayMetrics().density;
        return (pxVal / scale);
    }

    /**
     * px Turn sp
     *
     * @param pxVal
     * @return
     */
    public static float px2sp(Context context, float pxVal) {
        return (pxVal / context.getResources().getDisplayMetrics().scaledDensity);
    }

}
package com.example.hhly_pc.enumuse;

import java.util.List;

/**
 * Created by hhly-pc on 2017/1/22.
 */
public class SearchContactInfo {
    private List<Persion> allConctDetailedInfo;
    private String searchName;

    public List<Persion> getAllConctDetailedInfo() {
        return allConctDetailedInfo;
    }

    public void setAllConctDetailedInfo(List<Persion> allConctDetailedInfo) {
        this.allConctDetailedInfo = allConctDetailedInfo;
    }

    public String getSearchName() {
        return searchName;
    }

    public void setSearchName(String searchName) {
        this.searchName = searchName;
    }
}

Concluding remarks: a rookie, the first time to write a blog, it is estimated that there will be a lot of bad things to do, you are welcome to see the official corrections (see how the code quality is). Then they learn from each other.

Posted by Luvac Zantor on Fri, 05 Apr 2019 10:51:30 -0700