怎么让textview呈现出一个黑色边框
主要有三种方式可以实现:
带有边框的透明图片
使用xml的shape设置
继承TextView覆写onDraw方法。
方法一:
带有透明图片的背景图,只要设置background="#00000"就可以了。
方法二:
通过shape来设置背景图片
首先一个textview_border.xml文件放在drawable文件夹里面
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" android:shape="rectangle" >
<solid android:color="#ffffff" />
<stroke android:width="1dip" android:color="#4fa5d5"/>
</shape>
为要添加边框的TextView添加一个background
android:background="@drawable/textview_border"
方法三:
编写一个继承TextView类的自定义组件,并在onDraw事件方法中画边框。
package com.example.test;
import android.annotation.SuppressLint;
import android.content.Context;
import android.graphics.Canvas;
import android.graphics.Paint;
import android.util.AttributeSet;
import android.widget.TextView;
@SuppressLint("DrawAllocation")
public class BorderTextView extends TextView{
public BorderTextView(Context context) {
super(context);
}
public BorderTextView(Context context, AttributeSet attrs) {
super(context, attrs);
}
private int sroke_width = 1;
@Override
protected void onDraw(Canvas canvas) {
Paint paint = new Paint();
// 将边框设为黑色
paint.setColor(android.graphics.Color.BLACK);
// 画TextView的4个边
canvas.drawLine(0, 0, this.getWidth() - sroke_width, 0, paint);
canvas.drawLine(0, 0, 0, this.getHeight() - sroke_width, paint);
canvas.drawLine(this.getWidth() - sroke_width, 0, this.getWidth() - sroke_width, this.getHeight() - sroke_width, paint);
canvas.drawLine(0, this.getHeight() - sroke_width, this.getWidth() - sroke_width, this.getHeight() - sroke_width, paint);
super.onDraw(canvas);
}
}
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke
android:width="1dp"
android:color="#000000"
/>
</shape>
在布局xml文件的txtView控件中添加
android:background="@drawable/txt_shape"
<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android" >
<stroke
android:width="1dp"
android:color="#000000"
/>
</shape>
在布局xml文件的txtView控件中添加
android:background="@drawable/txt_shape"