TextView是Android中常用的一个控件,用于显示文本内容。实现placeholder效果可以通过以下几种方式:
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:hint="请输入内容"
/>
TextView textView = findViewById(R.id.text_view);
textView.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) {
}
@Override
public void afterTextChanged(Editable s) {
if (s.length() == 0) {
textView.setText("请输入内容");
}
}
});
public class PlaceholderTextView extends TextView {
private String placeholderText;
public PlaceholderTextView(Context context) {
super(context);
}
public PlaceholderTextView(Context context, AttributeSet attrs) {
super(context, attrs);
init(attrs);
}
public PlaceholderTextView(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
init(attrs);
}
private void init(AttributeSet attrs) {
TypedArray typedArray = getContext().obtainStyledAttributes(attrs, R.styleable.PlaceholderTextView);
placeholderText = typedArray.getString(R.styleable.PlaceholderTextView_placeholderText);
typedArray.recycle();
}
@Override
protected void onDraw(Canvas canvas) {
super.onDraw(canvas);
if (getText().length() == 0 && placeholderText != null) {
Paint paint = getPaint();
paint.setColor(getCurrentTextColor());
paint.setTextSize(getTextSize());
paint.setTextAlign(Paint.Align.LEFT);
canvas.drawText(placeholderText, getPaddingLeft(), getBaseline(), paint);
}
}
public void setPlaceholderText(String placeholderText) {
this.placeholderText = placeholderText;
invalidate();
}
}
在布局文件中使用自定义的PlaceholderTextView:
<com.example.app.PlaceholderTextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
app:placeholderText="请输入内容"
/>
以上就是实现TextView的placeholder效果的几种方法。
腾讯云相关产品和产品介绍链接地址:
领取专属 10元无门槛券
手把手带您无忧上云