这是效果图:
话不多数先上布局,我用的是线性布局:
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_margin="@dimen/padding"
android:background="@drawable/gray_corner_edit_input_bg"
android:orientation="vertical"
android:padding="@dimen/half_padding">
android:id="@+id/count_edit"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="@null"
android:gravity="top|left"
android:inputType="textMultiLine"
android:minLines="3"
android:paddingBottom='@dimen/half_padding'
android:textColor="@color/black"
android:textColorHint="@color/text_color"
android:textSize="@dimen/small_text_size"/>
android:id="@+id/letter_count"
style="@style/MDWrapContentGrayTextStyle"
android:layout_width="wrap_content"
android:layout_gravity="right"
android:text="0/150"/>
</LinearLayout>
接下来就是要通过代码还控制了:
//
public class EditTextCount extends RelativeLayout {
private EditText etContent;//文本框
privateTextView tvNum;//字数显示TextView
private int MaxNum=150;//最大字符
//空参构造和有参构造
public EditTextCount(Context context) {
this(context, null);
}
public EditTextCount(Context context,AttributeSet attrs) {
super(context,attrs);
LayoutInflater.from(context).inflate(R.layout.view_count_layout, this, true);
etContent= (EditText) findViewById(R.id.count_edit);
tvNum= (TextView) findViewById(R.id.letter_count);
intlength =etContent.getText().toString().length();
tvNum.setText(length +"/"+MaxNum);
//设置最大长度
etContent.setFilters(newInputFilter[]{newInputFilter.LengthFilter(MaxNum)});
//监听输入
etContent.addTextChangedListener(mTextWatcher);
}
//设置最大字数
public voidsetLength(intnum){
MaxNum= num;
etContent.setFilters(newInputFilter[]{newInputFilter.LengthFilter(MaxNum)});
intlength =etContent.getText().toString().length();
tvNum.setText(length +"/"+MaxNum);
}
//设置框内的hint内容
public void setEtHint(intstr){
etContent.setHint(str);
}
//设置内容
public void setEtText(String str){
etContent.setText(str);
}
// 获取输入内容
public String getText(){
return etContent.getText().toString();
}
//主要还是通过给EditText 设置 TextWatcher 来监听
private TextWatcher mTextWatcher=new TextWatcher() {
public voidafterTextChanged(Editable s) {
intlength =etContent.getText().toString().length();
tvNum.setText(length +"/"+MaxNum);
}
public void beforeTextChanged(CharSequence s, intstart, intcount,intafter) {}
public void onTextChanged(CharSequence s, intstart, intbefore,intcount) {}
};
网友评论