简体   繁体   中英

Android Scrollable TextView Border

I have a textView in my app within which I display text and graphics.

Once the content becomes too big for the constraints of the textView, it scrolls.

Everything works perfectly, however, I want to add a border around it. I looked here on SO and elsewhere on the internet and the only solutions I can find are adding a border around the background and then applying the background to said TextView. This is great, however when we scroll, the content is obviously displayed over the border like so:

在此处输入图片说明

Now obviously, I know why this is happening, (because the border is simply part of the background), however I don't know how to bring the border above the content.

The only XML I have is the background shape, everything else is done programatically, so I'm looking for a solution which can be applied to my situation.

XML

<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item>
 <shape android:shape="rectangle">
 <solid android:color="#ffeeeeee"/>
 <stroke
 android:width="15dp"
 android:color="#000000"
 />
 </shape>
</item>
</selector>

Java Code (Class extends TextView)

textLayout = new RelativeLayout(context);       
RelativeLayout.LayoutParams textParams = new RelativeLayout.LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT);
textParams.addRule(RelativeLayout.CENTER_HORIZONTAL);

setTextColor(Color.BLACK);
setGravity(Gravity.CENTER_HORIZONTAL);  
setTextSize(size);
setMovementMethod(new ScrollingMovementMethod());

setBackgroundResource(R.drawable.textbg);
textLayout.setPadding(xPadding, yPadding, xPadding, yPadding);

Bitmap testPic= BitmapFactory.decodeResource(getResources(), R.drawable.pic1);      
Bitmap testPic2= BitmapFactory.decodeResource(getResources(), R.drawable.pic2);         

SpannableStringBuilder builder = new SpannableStringBuilder();
builder.append(Html.fromHtml(someText)).append(" ");
builder.setSpan(new ImageSpan(context, testPic),
builder.length() - 1, builder.length(), 0);
builder.append(Html.fromHtml(someMoreText)).append(" ");
builder.setSpan(new ImageSpan(context, testPic2),
builder.length() - 1, builder.length(), 0);

your "border" has 15dp, so declare in dimen.xml something like this:

<resources>
    <dimen name="border_width">15dp</dimen>
</resources>

and use it as a padding in your custom TextView :

int pad = getResources().getDimensionPixelSize(R.dimen.border_width);
setPadding(pad, pad, pad, pad);

or if your view is defined in layout xml simply add "android:padding" attribute

EDIT:

you can also add <padding> inside your <shape> and define top / left / right / bottom padding:

<shape android:shape="rectangle">
    ...
    <padding .../>
</shape>

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM