104 lines
2.7 KiB
Java
104 lines
2.7 KiB
Java
package com.xscm.moduleutil.widget;
|
|
|
|
import android.content.Context;
|
|
import android.text.Editable;
|
|
import android.text.InputFilter;
|
|
import android.text.TextWatcher;
|
|
import android.util.AttributeSet;
|
|
import android.view.LayoutInflater;
|
|
import android.widget.EditText;
|
|
import android.widget.LinearLayout;
|
|
import android.widget.TextView;
|
|
|
|
import com.xscm.moduleutil.R;
|
|
|
|
/**
|
|
*@author
|
|
*@data 2025/5/15
|
|
*@description: 输入框添加字数文字提示
|
|
*/
|
|
public class CustomEditText extends LinearLayout {
|
|
|
|
private EditText editText;
|
|
private TextView lengthTextView;
|
|
private int maxLength = 100; // 默认最大长度
|
|
|
|
public CustomEditText(Context context) {
|
|
super(context);
|
|
init(context);
|
|
}
|
|
|
|
public CustomEditText(Context context, AttributeSet attrs) {
|
|
super(context, attrs);
|
|
init(context);
|
|
}
|
|
|
|
public CustomEditText(Context context, AttributeSet attrs, int defStyleAttr) {
|
|
super(context, attrs, defStyleAttr);
|
|
init(context);
|
|
}
|
|
|
|
private void init(Context context) {
|
|
// 加载布局文件
|
|
LayoutInflater.from(context).inflate(R.layout.custom_edit_text_layout, this, true);
|
|
|
|
// 找到 EditText 和 TextView 的引用
|
|
editText = findViewById(R.id.edit_text);
|
|
lengthTextView = findViewById(R.id.length_text_view);
|
|
|
|
// 初始化监听器
|
|
editText.addTextChangedListener(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) {
|
|
updateLengthDisplay();
|
|
}
|
|
|
|
@Override
|
|
public void afterTextChanged(Editable s) {}
|
|
});
|
|
|
|
// 设置默认的最大长度
|
|
setMaxLength(maxLength);
|
|
}
|
|
|
|
/**
|
|
* 设置最大长度
|
|
*/
|
|
public void setMaxLength(int maxLength) {
|
|
this.maxLength = maxLength;
|
|
editText.setFilters(new InputFilter[]{new InputFilter.LengthFilter(maxLength)});
|
|
updateLengthDisplay(); // 初始化显示
|
|
}
|
|
|
|
/**
|
|
* 更新显示的字数
|
|
*/
|
|
private void updateLengthDisplay() {
|
|
int currentLength = editText.getText().length();
|
|
lengthTextView.setText(currentLength + "/" + maxLength);
|
|
}
|
|
|
|
/**
|
|
* 设置提示文本
|
|
*/
|
|
public void setHint(String hint) {
|
|
editText.setHint(hint);
|
|
}
|
|
|
|
/**
|
|
* 获取当前文本
|
|
*/
|
|
public String getText() {
|
|
return editText.getText().toString();
|
|
}
|
|
|
|
/**
|
|
* 设置文本
|
|
*/
|
|
public void setText(String text) {
|
|
editText.setText(text);
|
|
}
|
|
} |