如何在android中的文本视图中设置边框和背景图像?

时间:2017-09-09 18:02:55

标签: android

as shown in image i want the border outside image but the image changes everytime as it comes from database我有一个文本视图,其中背景图像来自数据库,除了该图像我还想添加边框到textview背景。 我使用RoundedBitmapDrawable为textview设置背景图像。

RoundedBitmapDrawable img=  getDrawableFromName(getResources().getString(R.string.not_available));

//this line sets the border from .xml file.
mytextview.setBackgroundDrawable(getResources().getDrawable(R.drawable.holiday_dateborder));

//this line sets image to background
mytextview.setBackgroundDrawable(img);


//my method to get image.
 public RoundedBitmapDrawable getDrawableFromName(String name){

        Resources res = getResources();
        int resourceId =getResources().getIdentifier(name,"drawable",getPackageName());
        Bitmap src = BitmapFactory.decodeResource(res,resourceId);
        RoundedBitmapDrawable dr = RoundedBitmapDrawableFactory.create(res, src);
        try {
            if(dr.getBitmap()!=null)
            {
                return dr;
            }
        }
        catch (Exception e)
        {
            return null;
        }
        return null;

    } 

2 个答案:

答案 0 :(得分:0)

您可以使用以下代码

<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >

    <RelativeLayout
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:background="@drawable/bg_border_grey"
        android:padding="2dp"
        >

        <TextView
            android:id="@+id/textView"
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:background="@mipmap/ic_launcher"
            />

    </RelativeLayout>

</RelativeLayout>

bg_border_grey.xml 将其添加到您的drawable文件夹中

<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <corners android:radius="0dp" />
    <solid android:color="@android:color/transparent" />
    <stroke
        android:width="1dp"
        android:color="#000000" />
</shape>

答案 1 :(得分:0)

尝试将其设置为文本视图上圆形边框的背景: -

<shape xmlns:android="http://schemas.android.com/apk/res/android"
android:shape="ring">

<stroke
    android:width="2dp"
     android:color="@color/blue" />
</shape>