Home > Software engineering >  Two different styles in single textview android
Two different styles in single textview android

Time:12-29

I am trying to merge two textview with two different styles.

enter image description here

In above pic, How to put that curved border textview at end of above text. Means at end of (6).There is an way to do it in html but border not displaying in html.

String html = "<p style=\"border:1px; border-style:solid; border-color:#FF0000; padding: 1em;\"> B1-993m </p>";
            holder.book2.setText(Html.fromHtml(
                    html,
                            Html.FROM_HTML_MODE_LEGACY));

Above code works if we put it in html file but not working in android.it seems in android some html styles not supported.is there any way to do it or something wrong in my html with android.

enter image description here

Flexlayout :

enter image description here

CodePudding user response:

Not sure about the HTML part i don't have much idea about HTML. What i understood from your question i think this can be done by SpannableString . All you have to do is create a Custom ReplacementSpan. To apply the Span you need to have the idea about the span indexes i.e where exactly you want to show the box . I have tried following way . Its just a sample class to get the idea you can modify the drawing as per your need color and style everything.

public class BoxedSpan extends ReplacementSpan {
@Override
public void draw(Canvas canvas, CharSequence text, int start, int end, float x, int top, int y, int bottom, Paint paint) {
    RectF rect = new RectF(x, top, x   measureText(paint, text, start, end), bottom);
    paint.setColor(Color.BLACK);
    paint.setStyle(Paint.Style.STROKE);
    canvas.drawRoundRect(rect, 10f, 10f, paint);
    paint.setStyle(Paint.Style.FILL);
    canvas.drawText(text, start, end, x, y, paint);
}
@Override
public int getSize(Paint paint, CharSequence text, int start, int end, Paint.FontMetricsInt fm) {
    return Math.round(measureText(paint, text, start, end));
}
private float measureText(Paint paint, CharSequence text, int start, int end) {
    return paint.measureText(text, start, end);
}
}

here is the sample code i tried :-

SpannableStringBuilder stringBuilder = new
            SpannableStringBuilder("Here is some text B1-38 B2-36");
    stringBuilder.setSpan(new BoxedSpan(), 18, 23, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    stringBuilder.setSpan(new BoxedSpan(), 24, stringBuilder.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
    textView.setText(stringBuilder);

Looks like it pretty much does the job . Give it a try.

CodePudding user response:

First of all, you can try to use ConstraintLayout, it will help you arrange all view elements properly, and those two rounded TextView can be done with adding rounded background to them. You don't need any html marking.

CodePudding user response:

You might be better suited to using a background drawable with rounded edges for the B1-38

  • Related