您的位置:首页 > 移动开发 > Android开发

android 为TextView添加边框

2014-08-06 16:09 375 查看

今天需要在TextView上面添加一个边框,但是TextView本身不支持边框,所以只能采用其他方式,在网上查询了一下,主要有三种方式可以实现1.带有边框的透明图片2.使用xml的shape设置3继承TextView覆写onDraw方法。

方法一:

带有透明图片的背景图,这个没有什么好将的,自己制作一个就行 ,然后设置background就可以了

方法二:

通过shape来设置背景图片

首先一个textview_border.xml文件放在drawable文件夹里面

[html] view plaincopy

<?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事件方法中画边框。

[java] view plaincopy

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布局内容如下:

[html] view plaincopy

<?xml version="1.0" encoding="utf-8"?>

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"

android:layout_width="match_parent"

android:layout_height="match_parent" >

<TextView

android:layout_width="120dp"

android:layout_height="80dp"

android:background="@drawable/textview_border"

android:text="方法二"

android:textColor="#FF000000"

android:id="@+id/test"

android:gravity="center"

android:layout_alignParentTop="true"

android:layout_marginTop="20dp"

android:layout_centerHorizontal="true"

/>

<com.example.test.BorderTextView

android:layout_width="120dp"

android:layout_height="80dp"

android:text="方法三"

android:id="@+id/test3"

android:gravity="center"

android:layout_alignParentBottom="true"

android:layout_marginBottom="20dp"

android:layout_centerHorizontal="true"

></com.example.test.BorderTextView>

</RelativeLayout>
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: