Creating Custom EditText containing TextIcon
In this tutorial i will show how to create a EditText which will show some info on right of EditText. Sometimes we need to show some kind of hint or data next to EditText but for that we have to add extra layout for showing that data. To solve this problem we will be creating our own Custom EditText as shown in below picture.
Logic for Custom EditText
The logic for custom EditText is to create a bitmap from drawable and then embed text in that bitmap and set this bitmap on right of custom EditText. Whenever text changes just update the text by redrawing the bitmap with updated text.
MyEditText.java
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
public BitmapDrawable writeOnDrawable( String text) { //get xml drawable Drawable drawable = getResources().getDrawable(R.drawable.rounded_rectange); //calculate width of label text icon **base on pure assumptions //just taken padding of 60 and assumed width of each text letter to be 22 int width=60+text.length()*22; //convert xml drawable to bitmap Bitmap bitmap = Bitmap.createBitmap(width, 100, Bitmap.Config.ARGB_8888); Canvas canvas = new Canvas(bitmap); drawable.setBounds(0, 0, canvas.getWidth(), canvas.getHeight()); drawable.draw(canvas); //prepare paint to draw Paint paint = new Paint(); paint.setStyle(Paint.Style.FILL); paint.setColor(Color.RED); paint.setTextSize(40); //start padding of 30 left y value is pure assumption canvas.drawText(text, 30, (int)(bitmap.getHeight() * 0.65), paint); BitmapDrawable bmd = new BitmapDrawable(bitmap); bmd.setBounds(0, 0, bmd.getIntrinsicWidth() , bmd.getIntrinsicHeight() ); return bmd; } |
In this code i have created Bitmap from xml drawable resource. This was done by using canvas. After that paint object is created to draw on that bitmap. Lots of values used in this code are assumed and are found by hit and trial Suggestions in this case are welcomed.
For further queries please comment .