發(fā)布動態(tài)帶標(biāo)簽 話題 @功能的EditText

最近項目中要求自己做一個發(fā)布話題和動態(tài)的功能,仿照微博的發(fā)布自己手?jǐn)]了一個自定義EditText舶治,支持話題標(biāo)簽添加分井,@某人標(biāo)簽,以及標(biāo)簽文字顏色的自定義霉猛,標(biāo)簽字符的自定義:直接上代碼:

首先 先寫atrrs文件:


    <attr name="topic_tag" format="string">

    <attr name="topic_text_color" format="color">

    <attr name="topic_person_color" format="color">

    <attr name="topic_person" format="string">

</declare-styleable>

然后直接上代碼:

package com.modian.framework.ui.view;

import android.content.Context;

import android.content.res.TypedArray;

import android.graphics.Color;

import android.text.Editable;

import android.text.Spannable;

import android.text.TextUtils;

import android.text.TextWatcher;

import android.text.style.ForegroundColorSpan;

import android.util.AttributeSet;

import android.view.KeyEvent;

import android.view.View;

import androidx.annotation.NonNull;

import androidx.annotation.Nullable;

import com.modian.framework.R;

import java.util.ArrayList;

import java.util.List;

/**

* 發(fā)布話題自定義 EditText

*

*   

*            android:id="@+id/editText"

*            android:layout_width="match_parent"

*            android:layout_height="wrap_content"

*            app:topic_text_color="#A128CE"  話題標(biāo)簽顏色

*            app:topic_person_color="#E18A21" @某人 標(biāo)簽的顏色

*            app:topic_tag="6"  話題標(biāo)簽字符

*            app:topic_person="Y"/>  @某人字符

*

*/

public class MDTopicEditTextViewextends androidx.appcompat.widget.AppCompatEditTextimplements TextWatcher, View.OnKeyListener {

public static final  int TOPIC_TYPE_TOPIC =1;//話題標(biāo)簽

    public static final  int TOPIC_TYPE_PERSON =2;//話題標(biāo)簽@某人

    private static final StringTOPIC_TAG ="#"; //默認(rèn)的話題標(biāo)簽前后標(biāo)識為 #

    private static final int TOPIC_TEXT_COLOR = Color.parseColor("#FF0000"); //默認(rèn)的話題標(biāo)簽文本顏色

    private static final int TOPIC_PERSON_COLOR = Color.parseColor("#FFCC00"); //默認(rèn)的話題標(biāo)簽文本顏色

    private static final StringTOPIC_PERSON ="@"; //默認(rèn)的話題@用戶的標(biāo)識為@

    private ListtopicList =new ArrayList<>(); //定義一個話題的list尺锚,存放插入的話題標(biāo)簽

    private Stringtopic_tag =TOPIC_TAG;

    private Stringtopic_person =TOPIC_PERSON;

    private int topic_text_color =TOPIC_TEXT_COLOR;

    private int topic_person_color =TOPIC_PERSON_COLOR;

    private int index = -1;

    private boolean isBack =false; //是否按了返回鍵

    public MDTopicEditTextView(@NonNull Context context) {

this(context,null);

    }

public MDTopicEditTextView(@NonNull Context context, @Nullable AttributeSet attrs) {

this(context,attrs, R.attr.editTextStyle);

    }

public MDTopicEditTextView(@NonNull Context context, @Nullable AttributeSet attrs, int defStyleAttr) {

super(context, attrs, defStyleAttr);

        TypedArray typedArray = context.obtainStyledAttributes(attrs,R.styleable.MDTopicEditTextView);

        topic_tag = typedArray.getString(R.styleable.MDTopicEditTextView_topic_tag);

        if(TextUtils.isEmpty(topic_tag)) {

topic_tag =TOPIC_TAG;

        }

topic_person = typedArray.getString(R.styleable.MDTopicEditTextView_topic_person);

        if(TextUtils.isEmpty(topic_person)) {

topic_person =TOPIC_TAG;

        }

topic_text_color = typedArray.getColor(R.styleable.MDTopicEditTextView_topic_text_color,TOPIC_TEXT_COLOR);

        topic_person_color = typedArray.getColor(R.styleable.MDTopicEditTextView_topic_person_color,TOPIC_PERSON_COLOR);

        init();

    }

private void init() {

//添加文本變化監(jiān)聽

        this.addTextChangedListener(this);

    }

public void setTopic(String topic){

setTopic(topic,TOPIC_TYPE_TOPIC); //默認(rèn)為話題標(biāo)簽

    }

/**

* 添加話題

    * @param topic 話題文本

*/

    public void setTopic(String topic,int type){

if(TextUtils.isEmpty(topic)){

return;

        }

String tagTopic ="";

        if(type ==TOPIC_TYPE_TOPIC) {

tagTopic =topic_tag + topic +topic_tag; //話題前后添加標(biāo)簽符號("#topic#")

        }else if(type ==TOPIC_TYPE_PERSON){

tagTopic =topic_person + topic; //話題前后添加標(biāo)簽符號("@topic")

        }

topicList.add(tagTopic);

        //獲取當(dāng)前光標(biāo)的位置

        int selectionStart = getSelectionStart();

        //獲取EditText上的文本內(nèi)容

        Editable editable = getText();

        if(selectionStart >=0){

// 插入話題

            editable.insert(selectionStart,tagTopic+" ");

            //移動光標(biāo)到最后

            setSelection(getSelectionStart());

            reFreshText(tagTopic);

        }

setOnKeyListener(this);

    }

/**

* 刷新UI,設(shè)置話題標(biāo)簽字體變色

    * @param tagTopic

    */

    private void reFreshText(String tagTopic) {

if (topicList.size() ==0)

return;

        // 重新設(shè)置span

        Editable editable = getText();

        int textLength = editable.length();

        int findPosition =0;

        for (int i =0; I

String objectText =topicList.get(i);

            while (findPosition <= textLength) {

// 獲取文本開始下標(biāo)

                findPosition = getText().toString().indexOf(objectText, findPosition);

                if (findPosition != -1) {

// 設(shè)置話題內(nèi)容前景色高亮

                    ForegroundColorSpan colorSpan;

                    if(objectText.startsWith(topic_tag))

colorSpan=new ForegroundColorSpan(topic_text_color);

else

                        colorSpan=new ForegroundColorSpan(topic_person_color);

                    editable.setSpan(colorSpan, findPosition, findPosition + objectText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                    findPosition += objectText.length();

                }else {

break;

                }

}

}

}

/**

* 光標(biāo)改變監(jiān)聽

    * @param selStart

    * @param selEnd

    */

    @Override

    protected void onSelectionChanged(int selStart, int selEnd) {

super.onSelectionChanged(selStart, selEnd);

        if(topicList ==null ||topicList.size() ==0){

return;

        }

int startPositon =0;

        int endPositon =0;

        String topicText ="";

        if(!isBack) {

for (int i =0; I

topicText =topicList.get(i);

                int length = getText().toString().length();

                startPositon = getText().toString().indexOf(topicText, startPositon);

                endPositon = startPositon + topicText.length();

                if (startPositon == -1) {

return;

                }

if (selStart > startPositon && selEnd <= endPositon-1) {

if ((endPositon +1) > length) {

setSelection(endPositon);

                    }else {

setSelection(endPositon +1);

                    }

}

startPositon = endPositon;

            }

}

isBack =false;

    }

@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 editablede) {

}

/**

* 鍵盤back鍵監(jiān)聽

    * @param v

    * @param keyCode

    * @param event

    * @return

    */

    @Override

    public boolean onKey(View v, int keyCode, KeyEvent event) {

if (keyCode == KeyEvent.KEYCODE_DEL && event.getAction() == KeyEvent.ACTION_DOWN) {

//返回鍵導(dǎo)致光標(biāo)的移動

            isBack =true;

            int selectionStart = getSelectionStart();

            int selectionEnd = getSelectionEnd();

            //如果光標(biāo)起始和結(jié)束在同一位置,說明是選中效果,直接返回 false 交給系統(tǒng)執(zhí)行刪除動作

            if (selectionStart != selectionEnd) {

if(index != -1) {

topicList.remove(index);

                    index = -1;

                }

return false;

            }

Editable editable = getText();

            String content = editable.toString();

            int lastPos =0;

            //遍歷判斷光標(biāo)的位置

            for (int i =0; I

String topic =topicList.get(i);

                lastPos = content.indexOf(topic, lastPos);

                if (lastPos != -1) {

if (selectionStart !=0 && selectionStart > lastPos && selectionStart <= (lastPos + topic.length())) {

//選中話題

                        setSelection(lastPos, lastPos + topic.length());

                        index = I;

return true;

                    }

}

lastPos += topic.length();

            }

}

return false;

    }

}

在xml中 直接使用就行啦:

<com.modian.framework.ui.view.MDTopicEditTextView

           android:id="@+id/editText"

            android:layout_width="match_parent"

           android:layout_height="wrap_content"

           app:topic_text_color="#A128CE"  話題標(biāo)簽顏色

            app:topic_person_color="#E18A21" @某人 標(biāo)簽的顏色

           app:topic_tag="6"  話題標(biāo)簽字符

           app:topic_person="Y"/>  @某人字符

來幾張效果圖:

image.png
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
  • 序言:七十年代末韩脏,一起剝皮案震驚了整個濱河市缩麸,隨后出現(xiàn)的幾起案子铸磅,更是在濱河造成了極大的恐慌赡矢,老刑警劉巖杭朱,帶你破解...
    沈念sama閱讀 219,366評論 6 508
  • 序言:濱河連續(xù)發(fā)生了三起死亡事件,死亡現(xiàn)場離奇詭異吹散,居然都是意外死亡弧械,警方通過查閱死者的電腦和手機(jī),發(fā)現(xiàn)死者居然都...
    沈念sama閱讀 93,521評論 3 395
  • 文/潘曉璐 我一進(jìn)店門空民,熙熙樓的掌柜王于貴愁眉苦臉地迎上來刃唐,“玉大人,你說我怎么就攤上這事界轩』ⅲ” “怎么了?”我有些...
    開封第一講書人閱讀 165,689評論 0 356
  • 文/不壞的土叔 我叫張陵浊猾,是天一觀的道長抖甘。 經(jīng)常有香客問我,道長葫慎,這世上最難降的妖魔是什么衔彻? 我笑而不...
    開封第一講書人閱讀 58,925評論 1 295
  • 正文 為了忘掉前任,我火速辦了婚禮偷办,結(jié)果婚禮上艰额,老公的妹妹穿的比我還像新娘。我一直安慰自己椒涯,他們只是感情好柄沮,可當(dāng)我...
    茶點故事閱讀 67,942評論 6 392
  • 文/花漫 我一把揭開白布。 她就那樣靜靜地躺著废岂,像睡著了一般铡溪。 火紅的嫁衣襯著肌膚如雪。 梳的紋絲不亂的頭發(fā)上泪喊,一...
    開封第一講書人閱讀 51,727評論 1 305
  • 那天棕硫,我揣著相機(jī)與錄音,去河邊找鬼袒啼。 笑死哈扮,一個胖子當(dāng)著我的面吹牛,可吹牛的內(nèi)容都是我干的蚓再。 我是一名探鬼主播滑肉,決...
    沈念sama閱讀 40,447評論 3 420
  • 文/蒼蘭香墨 我猛地睜開眼,長吁一口氣:“原來是場噩夢啊……” “哼摘仅!你這毒婦竟也來了靶庙?” 一聲冷哼從身側(cè)響起,我...
    開封第一講書人閱讀 39,349評論 0 276
  • 序言:老撾萬榮一對情侶失蹤娃属,失蹤者是張志新(化名)和其女友劉穎六荒,沒想到半個月后护姆,有當(dāng)?shù)厝嗽跇淞掷锇l(fā)現(xiàn)了一具尸體,經(jīng)...
    沈念sama閱讀 45,820評論 1 317
  • 正文 獨居荒郊野嶺守林人離奇死亡掏击,尸身上長有42處帶血的膿包…… 初始之章·張勛 以下內(nèi)容為張勛視角 年9月15日...
    茶點故事閱讀 37,990評論 3 337
  • 正文 我和宋清朗相戀三年卵皂,在試婚紗的時候發(fā)現(xiàn)自己被綠了。 大學(xué)時的朋友給我發(fā)了我未婚夫和他白月光在一起吃飯的照片砚亭。...
    茶點故事閱讀 40,127評論 1 351
  • 序言:一個原本活蹦亂跳的男人離奇死亡灯变,死狀恐怖,靈堂內(nèi)的尸體忽然破棺而出捅膘,到底是詐尸還是另有隱情添祸,我是刑警寧澤,帶...
    沈念sama閱讀 35,812評論 5 346
  • 正文 年R本政府宣布寻仗,位于F島的核電站膝捞,受9級特大地震影響,放射性物質(zhì)發(fā)生泄漏愧沟。R本人自食惡果不足惜蔬咬,卻給世界環(huán)境...
    茶點故事閱讀 41,471評論 3 331
  • 文/蒙蒙 一、第九天 我趴在偏房一處隱蔽的房頂上張望沐寺。 院中可真熱鬧林艘,春花似錦、人聲如沸混坞。這莊子的主人今日做“春日...
    開封第一講書人閱讀 32,017評論 0 22
  • 文/蒼蘭香墨 我抬頭看了看天上的太陽究孕。三九已至啥酱,卻和暖如春,著一層夾襖步出監(jiān)牢的瞬間厨诸,已是汗流浹背镶殷。 一陣腳步聲響...
    開封第一講書人閱讀 33,142評論 1 272
  • 我被黑心中介騙來泰國打工, 沒想到剛下飛機(jī)就差點兒被人妖公主榨干…… 1. 我叫王不留微酬,地道東北人绘趋。 一個月前我還...
    沈念sama閱讀 48,388評論 3 373
  • 正文 我出身青樓,卻偏偏與公主長得像颗管,于是被迫代替她去往敵國和親陷遮。 傳聞我的和親對象是個殘疾皇子,可洞房花燭夜當(dāng)晚...
    茶點故事閱讀 45,066評論 2 355