• After 15+ years, we've made a big change: Android Forums is now Early Bird Club. Learn more here.

SpannableStringBuilder is clearing formatting!?

dipetca

Lurker
hello everybody
i'm learning to program in Java for Android. i'm trying to format text on a TextView using SpannableStringBuilder. but, for some reason, when the code gets to line 42, the first part of the text loses the formatting.
(button is a simple Button and textView is a simple TextView, both defined in activity_main.xml)

Java:
package com.example.myapplication;

import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.text.SpannableStringBuilder;
import android.text.Spanned;
import android.text.style.RelativeSizeSpan;
import android.view.View;
import android.widget.Button;
import android.widget.TextView;

public class MainActivity extends AppCompatActivity {
    boolean answer_ison;
    Button button;
    TextView textView;
    SpannableStringBuilder str;
    final RelativeSizeSpan title_span = new RelativeSizeSpan(1.6f);

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        answer_ison = true;
        button = findViewById(R.id.button);
        textView = findViewById(R.id.textView);
        str = new SpannableStringBuilder();

        button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (answer_ison) {
                    str.clear();
                    str.clearSpans();
                    str.append("Question:\n", title_span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    str.append("The question goes here :)");
                    button.setText("Show Answer");
                    answer_ison = false;
                }
                else {
                    str.append("\n\nAnswer:\n", title_span, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                    str.append("Aand the answer goes here");
                    button.setText("Next Question");
                    answer_ison = true;
                }
                textView.setText(str);
            }
        });

    }
}

first its like this (its what I expect):
Screenshot_20190714-105219_My Application.jpg

but if I press the button, it seems to clear the the formatting of the first part:
Screenshot_20190714-105222_My Application.jpg

any help is apreciated. thanks in advance!
 
It's probably a quirk of using the SPAN_EXCLUSIVE_EXCLUSIVE flag.
I'd probably do this by using two TextViews. Use one for the question - always visible. Make the other TextView contain the answer, and it's initially not visible. Clicking on the button will make it visible.
 
Back
Top Bottom