自定义编辑EditText打tag标签View

package cn.baryon.here.ui;

import android.content.Context;
import android.graphics.BitmapFactory;
import android.graphics.Color;
import android.graphics.drawable.GradientDrawable;
import android.text.Editable;
import android.text.TextWatcher;
import android.util.AttributeSet;
import android.util.Log;
import android.view.Gravity;
import android.view.KeyEvent;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.TextView;

import com.yuzhi.fine.R;

import java.util.ArrayList;

import cn.baryon.here.ui.heartview.UIUtils;

/**
 * Created by mac on 17/7/29.
 */

public class TagView extends ViewGroup {

    private ImageView imageView;
    private EditText mEditText;
    private ArrayList<TextView> textViews = new ArrayList<>();
    private MarginLayoutParams mParams;
    private int childHeight = 24;
    private String tagSpace = ",";
    private String text = "";
    private String beforeText = "";
    private ArrayList<String> textArray = new ArrayList<>();



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

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

    private void init() {
        MarginLayoutParams params = new MarginLayoutParams(UIUtils.dp2px(34), UIUtils.dp2px(34));
        imageView = new ImageView(getContext());
        imageView.setLayoutParams(params);
        imageView.setImageBitmap(BitmapFactory.decodeResource(getResources(), R.drawable.tag_icon));
        addView(imageView);

        mParams = new ViewGroup.MarginLayoutParams(LayoutParams.WRAP_CONTENT,UIUtils.dp2px(childHeight));
        int margin = 5;
        mParams.leftMargin = UIUtils.dp2px(margin);  //dp转成px
        mParams.rightMargin = UIUtils.dp2px(margin);
        mParams.topMargin = UIUtils.dp2px(margin);
        mParams.bottomMargin = UIUtils.dp2px(margin);

        mEditText = new EditText(getContext());
        mEditText.setLayoutParams(mParams);
        int padding = UIUtils.dp2px(2);
        mEditText.setPadding(padding, padding, padding, padding);
        mEditText.setTextSize(13);
        mEditText.setTextColor(Color.rgb(67, 67, 67));
        mEditText.setBackgroundColor(Color.rgb(255, 255, 255));
        mEditText.setHint("打标签");
        mEditText.setFocusable(true);
        mEditText.setOnKeyListener(onKeyListener);
        mEditText.addTextChangedListener(textWatcher);
        mEditText.setVisibility(INVISIBLE);
        addView(mEditText);
        Log.i("cxblog","");
    }

    private TextView getTextView(String str){
        TextView tv = new TextView(getContext());
        tv.setLayoutParams(mParams);
        int padding = UIUtils.dp2px(4);
        tv.setPadding(padding, padding, padding, padding);
        tv.setGravity(Gravity.CENTER);
        tv.setText(str);
        tv.setTextSize(12);
        int color = Color.rgb(83, 195, 85);
        tv.setTextColor(color);
        GradientDrawable bgDrawable = new GradientDrawable();
        bgDrawable.setCornerRadius(UIUtils.dp2px(childHeight/2));
        bgDrawable.setStroke(UIUtils.dp2px(0.5), color);
        //bgDrawable.setColor(color);
        tv.setBackground(bgDrawable);
        return tv;
    }

    public void configWithText(String str){
        text = str;
        if (str.length() == 0) return;
        for (int i = 0; i<textViews.size(); i++) removeView(textViews.get(i));
        textViews.clear();
        textArray.clear();
        textArray = getArrayWithText(str);
        Log.i("cxblog","<"+text+">" +"  "+getByteLength(text));
        for (int i = 0; i<textArray.size(); i++){
            TextView tv = getTextView(textArray.get(i));
            addView(tv);
            textViews.add(tv);
        }
    }
    public String getText(){
        return text;
    }
    public void setEnabled(boolean b){
        if (b == true){
            mEditText.setVisibility(VISIBLE);
        }else {
            mEditText.setVisibility(INVISIBLE);
        }
    }

    private TextWatcher textWatcher = new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            beforeText = charSequence.toString();
//            Log.i("cxblog","beforeTextChanged:"+charSequence.toString());
        }
        @Override
        public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
            String afterText = charSequence.toString();
            if (afterText.equals(",") || afterText.equals(",")){
                mEditText.setText("");
                return;
            }
            if (afterText.length() > 0){
                String endString = afterText.substring(afterText.length()-1);
//                Log.i("cxblog","       endString:---"+endString);
                if (endString.equals(",") || endString.equals(",")){
                    comeToAnEnd(beforeText);
                }
            }
        }
        @Override
        public void afterTextChanged(Editable editable) {}
    };
    private void comeToAnEnd(String str){
        if (str.length() == 0) return;
        textArray.add(str);
        text = getTextWithArray(textArray);
        if (textArray.size() > 8 || getByteLength(text) > 16){
            textArray.remove(textArray.size()-1);
            text = getTextWithArray(textArray);
        }
        mEditText.setText("");
        configWithText(text);
    }

    private OnKeyListener onKeyListener = new OnKeyListener() {
        @Override
        public boolean onKey(View view, int keyCode, KeyEvent keyEvent) {
            if (keyEvent.getAction() == KeyEvent.ACTION_DOWN){
                if (keyCode == KeyEvent.KEYCODE_ENTER) {
                    //Log.i("cxblog","回车键");
                    comeToAnEnd(mEditText.getText().toString());
                    // 关闭键盘
//                    Activity activity = (Activity)getContext();
//                    InputMethodManager imm = (InputMethodManager)activity.getSystemService(Context.INPUT_METHOD_SERVICE);
//                    if (imm.isActive() && activity.getCurrentFocus() != null) {
//                        if (activity.getCurrentFocus().getWindowToken() != null) {
//                            imm.hideSoftInputFromWindow(activity.getCurrentFocus().getWindowToken(), InputMethodManager.HIDE_NOT_ALWAYS);
//                        }
//                    }
                    return true;
                }
                if (keyCode == KeyEvent.KEYCODE_DEL){
                    //Log.i("cxblog","删除键");
                    if (mEditText.getText().toString().length() == 0){
                        if (textViews.size()>0){
                            textArray.remove(textArray.size()-1);
                            text = getTextWithArray(textArray);
                            Log.i("cxblog","<"+text+">" +"  "+getByteLength(text));
                            TextView lastTv = textViews.get(textViews.size()-1);
                            textViews.remove(lastTv);
                            removeView(lastTv);
                        }
                    }
                }
                return false;
            }else {
                if (keyCode == KeyEvent.KEYCODE_BACK){
                    return false;
                }else {
                    return true;
                }
            }
        }
    };

    private String getTextWithArray(ArrayList<String> array){
        String text = "";
        for (int i = 0; i<array.size(); i++){
            String str = array.get(i);
            if (i == array.size()-1){
                text = text+str;
            }else {
                text = text+str+tagSpace;
            }
        }
        return text;
    }
    private ArrayList<String> getArrayWithText(String string){
        ArrayList<String> array = new ArrayList();
        String[] strings = string.split(tagSpace);
        for (int i = 0; i<strings.length; i++){
            String str = strings[i];
            array.add(str);
        }
        return array;
    }
    private int getByteLength(String str){
        byte[] buff = str.getBytes();
        int length = buff.length;
        return (length+1)/2;
    }

    @Override
    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
        super.onMeasure(widthMeasureSpec, heightMeasureSpec);
        measureChildren(widthMeasureSpec,heightMeasureSpec);
        int widthMode = MeasureSpec.getMode(widthMeasureSpec);
        int widthSize = MeasureSpec.getSize(widthMeasureSpec);
        int heightMode = MeasureSpec.getMode(heightMeasureSpec);
        int heightSize = MeasureSpec.getSize(heightMeasureSpec);
    }

    @Override
    protected void onLayout(boolean changed, int l, int t, int r, int b) {
        imageView.layout(UIUtils.dp2px(10),0,UIUtils.dp2px(10)+imageView.getMeasuredWidth(), imageView.getMeasuredHeight());
        int x = imageView.getRight()+UIUtils.dp2px(5);
        int y = (getMeasuredHeight()-UIUtils.dp2px(childHeight))/2;
        for (int i = 0; i < textViews.size(); i++) {
            View child = textViews.get(i);
            MarginLayoutParams mp = ((MarginLayoutParams) child.getLayoutParams());
            int width = child.getMeasuredWidth();
            if (width < UIUtils.dp2px(childHeight)) width = UIUtils.dp2px(childHeight);
            child.layout(x, y, x+width, y+child.getMeasuredHeight());
            x += (width + mp.leftMargin);
        }
        int mEditTextW = getMeasuredWidth()-x-UIUtils.dp2px(5);
        mEditText.layout(x, y, x+mEditTextW, y+mEditText.getMeasuredHeight());
    }

    @Override
    public LayoutParams generateLayoutParams(AttributeSet attrs) {
        MarginLayoutParams mp = new MarginLayoutParams(getContext(), attrs);
        return mp;
    }
}

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值