为EditText添加千位逗号分割

1558004600671_video.gif
<declare-styleable name="StoreCostSetCell">
        <attr name="store_LeftTitle" format="string" />
        <attr name="store_RightMoney" format="string" />
</declare-styleable>

布局文件

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:id="@+id/parentView"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:focusableInTouchMode="true"
    android:paddingStart="16dp"
    android:paddingTop="20dp"
    android:paddingEnd="16dp"
    android:paddingBottom="20dp"
    tools:ignore="MissingDefaultResource">

    <TextView
        android:id="@+id/tvTitle"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textColor="@color/colorTextBlack"
        android:textSize="16sp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        tools:text="门店月租金" />

    <EditText
        android:id="@+id/edMoney"
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_marginStart="50dp"
        android:background="@null"
        android:gravity="end"
        android:hint="¥请输入金额"
        android:inputType="number"
        android:textColor="@color/colorPrimary"
        android:textColorHint="#B2B7BE"
        android:textSize="18sp"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvTitle"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toEndOf="@+id/tvTitle" />

    <TextView
        android:id="@+id/tvUnit"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginEnd="3dp"
        android:text="¥"
        android:textColor="@color/colorPrimary"
        android:textSize="14sp"
        android:visibility="gone"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvTitle"
        app:layout_constraintEnd_toStartOf="@+id/edMoneyGone" />


    <EditText
        android:id="@+id/edMoneyGone"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@null"
        android:clickable="false"
        android:focusable="false"
        android:longClickable="false"
        android:textColor="@color/colorPrimary"
        android:textSize="18sp"
        android:visibility="invisible"
        app:layout_constraintBaseline_toBaselineOf="@+id/tvTitle"
        app:layout_constraintEnd_toEndOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

代码实现

/**
 * Created by liuqian on 2019/3/14 19:36
 * Describe:
 */
class StoreCostSetCell @JvmOverloads constructor(context: Context, attrs: AttributeSet? = null, defStyleAttr: Int = 0) : ConstraintLayout(context, attrs, defStyleAttr) {

    private val view: View = LayoutInflater.from(context).inflate(R.layout.store_cell_cost_set, this)
    private val tvTitle: TextView
    private val edMoney: EditText
    private val tvUnit: TextView
    private val edMoneyGone: EditText  //不可见的那个edittext  用来控制单位的位置

    init {
        val a = context.obtainStyledAttributes(attrs, R.styleable.StoreCostSetCell)
        val tvLeftContent = a.getString(R.styleable.StoreCostSetCell_store_LeftTitle)
        val tvRightContent = a.getString(R.styleable.StoreCostSetCell_store_RightMoney)
        a.recycle()
        tvTitle = view.findViewById(R.id.tvTitle)
        edMoney = view.findViewById(R.id.edMoney)
        tvUnit = view.findViewById(R.id.tvUnit)
        edMoneyGone = view.findViewById(R.id.edMoneyGone)
        setListener()
        tvTitle.text = tvLeftContent
        edMoney.setText(tvRightContent)
    }

    private fun setEdHint(isShowHintConent: Boolean = true) {
        if (isShowHintConent)
            edMoney.hint = SpannableString("¥请输入金额").apply {
                setSpan( //修改颜色
                        ForegroundColorSpan(Color.parseColor("#B2B7BE")),
                        0,
                        this.length,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )

                setSpan( //单位的大小
                        RelativeSizeSpan(0.78f),
                        0,
                        1,
                        Spanned.SPAN_EXCLUSIVE_EXCLUSIVE
                )
            }
        else edMoney.hint = ""
    }

    private fun setListener() {
        edMoney.setOnFocusChangeListener { _, hasFocus ->
            if (hasFocus) {
                if (edMoney.length() == 0) {
                    setEdHint(false) //便显示hint
                    tvUnit.visibility = View.VISIBLE
                }
            } else {
                val content = edMoney.text.toString()
                if (content.isNotEmpty()) { //有内容
                    tvUnit.visibility = View.VISIBLE
                } else {
                    setEdHint(true) //显示hint
                    tvUnit.visibility = View.GONE
                }
            }
        }
        edMoney.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                //以下为加入分割逗号  千位分割
                if (!edMoney.hasFocus()) return
                val realString = s.toString().replace(",", "")
                val stringBuild = StringBuilder() //保存变化的数据
                if (realString.length > 3) { //大于 3 才会添加
                    //开始下标
                    var startAddIndex: Int = if (realString.length % 3 == 0) {
                        3
                    } else {
                        realString.length % 3
                    }
                    for (i in 0 until realString.length) {

                        if (startAddIndex == i) {
                            stringBuild.append(",")
                            startAddIndex += 3 //下一个添加逗号的下标
                        }
                        stringBuild.append(realString[i].toString())

                    }

                    if (stringBuild.toString() != s.toString()) {  //别进入死循环
                        edMoney.setText(stringBuild.toString())
                        edMoney.setSelection(edMoney.length())
                        edMoneyGone.text = edMoney.text
                    }
                } else {
                    //此时可能会存在逗号  1,23
                    if (edMoney.text.toString() != realString) {
                        edMoney.setText(realString)
                        edMoney.setSelection(edMoney.length())
                    }
                    edMoneyGone.setText(realString)
                }
            }
        })
    }

    private fun setRightContent(string: String) {
        edMoney.setText(string)
    }

    private fun getMoney(): String {
        return edMoney.text.toString().replace(",", "")
    }
}
最后编辑于
©著作权归作者所有,转载或内容合作请联系作者
【社区内容提示】社区部分内容疑似由AI辅助生成,浏览时请结合常识与多方信息审慎甄别。
平台声明:文章内容(如有图片或视频亦包括在内)由作者上传并发布,文章内容仅代表作者本人观点,简书系信息发布平台,仅提供信息存储服务。

相关阅读更多精彩内容

  • 问答题47 /72 常见浏览器兼容性问题与解决方案? 参考答案 (1)浏览器兼容问题一:不同浏览器的标签默认的外补...
    _Yfling阅读 14,168评论 1 92
  • ¥开启¥ 【iAPP实现进入界面执行逐一显】 〖2017-08-25 15:22:14〗 《//首先开一个线程,因...
    小菜c阅读 7,358评论 0 17
  • 翻译自“Collection View Programming Guide for iOS” 0 关于iOS集合视...
    lakerszhy阅读 4,076评论 1 22
  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,674评论 1 32
  • 一、温故而知新 1. 内存不够怎么办 内存简单分配策略的问题地址空间不隔离内存使用效率低程序运行的地址不确定 关于...
    SeanCST阅读 8,135评论 0 27

友情链接更多精彩内容