Android系统本身提供的EditText组件并不支持边框,但可以对edittext进行扩展来添加边框。我们可以使用如下两种方法为组件添加边框。
1. 编写一个继承EditText类的自定义组件,并在onDraw事件方法中画边框。
2. 使用9-patch格式的图像作为TextView的背景图来设置边框(这个背景图需要带一个边框)。
3.使用xml的方式
在onDraw事件方法中画边框非常容易,只需要画EditText组件的上、下、左、右四个边即可。这个自定义组件的代码如下:
public class BorderTextView extends EditText { @Override protected void onDraw(Canvas canvas) { super.onDraw(canvas); Paint paint = new Paint(); // 将边框设为黑色 paint.setColor(android.graphics.Color.BLACK); paint.setStrokeWidth(1); // 画TextView的4个边 canvas.drawLine(0, 0, this.getWidth() - 1, 0, paint); canvas.drawLine(0, 0, 0, this.getHeight() - 1, paint); canvas.drawLine(this.getWidth() - 1, 0, this.getWidth() - 1, this.getHeight() - 1, paint); canvas.drawLine(0, this.getHeight() - 1, this.getWidth() - 1, this.getHeight() - 1, paint); setBackgroundColor(Color.TRANSPARENT); } private Paint mPaint; public BorderTextView(Context context) { super(context); // TODO Auto-generated constructor stub mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.GREEN); setBackgroundColor(Color.TRANSPARENT);//透明背景 } public BorderTextView(Context context, AttributeSet attrs) { super(context, attrs); // TODO Auto-generated constructor stub mPaint = new Paint(); mPaint.setStyle(Paint.Style.STROKE); mPaint.setColor(Color.GRAY); setBackgroundColor(Color.TRANSPARENT);//背景透明 } }
这样我们的输入框的边框就有自己想要的的原色了,之所以这么弄,是因为在动态添加输入框时候。安卓没提供相应的接口去改变输入框边框的颜色,大小。
2.
虽然可以直接使用带边框的图像作为组件的背景来设置边框,但当EditTextView的大小变化时,背景图像上的边框也随之变粗或变细,这样看起来并不太舒服。为了解决这个问题,可以采用9-patch格式的图像来作为 EditText组件的背景图。我们可以使用<Android SDK安装目录>\tools\draw9patch.bat命令来启动“Draw 9-patch”工具。制作9-patch格式的图像也很简单,将事先做好的带边框的png图像(必须是png格式的图像)用这个工具打开,并在外边框的上方和左侧画一个象素点,然后保存即可,如图1所示。9-patch格式的图像必须以9.png结尾,例如,abc.9.png。在生成完9-patch格式的图像后,使用<EditText>标签的android:background属性指定相应的图像资源即可。
图1![]()
3.如果只是固定的一个。那么有下面的方法
第一步:为了更好的比较,准备两个一模一样的EditText(当Activity启动时,焦点会在第一个EditText上,如果你不希望这样只需要写一个高度和宽带为0的EditText即可避免,这里就不这么做了),代码如下:
- <EditText
- android:layout_width="fill_parent"
- android:layout_height="36dip"
安卓_重写Edittext,画边框
最新推荐文章于 2024-07-26 16:34:49 发布