MyEditText.java
package com.example.myapplication24.UI;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Canvas;
import android.graphics.Color;
import android.graphics.Paint;
import android.util.AttributeSet;
import com.example.myapplication24.R;
public class MyEditText extends androidx.appcompat.widget.AppCompatEditText {
private String mhint = "";
private Paint mPaint;
private Context mContext;
private float paddingLeft = 0 ;
public MyEditText(Context context) {
super(context);
this.mContext = context;
init();
}
public MyEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.mContext = context;
init();
TypedArray a = mContext.obtainStyledAttributes(attrs,R.styleable.MyEditText);
mhint = a.getString(R.styleable.MyEditText_mhint);
setPadding((int)(mPaint.measureText(mhint)),getPaddingTop(),getPaddingRight(),getPaddingBottom());
a.recycle();
}
public MyEditText(Context context, AttributeSet attrs, int defStyleAttr) {
super(context, attrs, defStyleAttr);
this.mContext = context;
init();
TypedArray a = context.obtainStyledAttributes(attrs,R.styleable.MyEditText,defStyleAttr,0);
mhint = a.getString(R.styleable.MyEditText_mhint);
setPadding((int)(mPaint.measureText(mhint)),getPaddingTop(),getPaddingRight(),getPaddingBottom());
a.recycle();
}
private void init() {
mPaint = new Paint();
mPaint.setTextSize(getTextSize());
mPaint.setColor(Color.GRAY);
paddingLeft = getPaddingLeft();
}
private int dp2px(float dp) {
return (int) (mContext.getResources().getDisplayMetrics().density * dp + 0.5f);
}
@Override
protected void onDraw(Canvas canvas) {
//Drawing mhint
canvas.drawText(mhint,dp2px(5),getHeight()*0.65f,mPaint);
super.onDraw(canvas);
}
}
布局.xml
<com.example.myapplication24.UI.MyEditText
android:layout_width="match_parent"
android:layout_height="wrap_content"
app:mhint="Username: "
android:text="asd"
></com.example.myapplication24.UI.MyEditText>
attrs.xml
<!--my hint-->
<attr name="mhint" format="string"/>
<declare-styleable name="MyEditText">
<attr name="mhint"/>
</declare-styleable>
</resources>
希望对后来者有所帮助...
演示