Alaa M.
Alaa M.

Reputation: 5273

Html formatted text in NumberPicker

I'm using a NumberPicker and I want to add a suffix for each number.

I know that I can do this:

picker.setFormatter(new NumberPicker.Formatter() {
    @Override
    public String format(int value) {
        return value + " suffix");
    }
});

But I want the suffix to be a subscript. So I tried this:

picker.setFormatter(new NumberPicker.Formatter() {
    @Override
    public String format(int value) {
        return value + " " + Html.fromHtml("<sub>suffix</sub>")
    }
});

But it's not working - the format is not applied; the suffix is not a subscript. That's obviously because fromHtml returns Spanned and then I'm converting it to String.

So can I apply an Html formatted string on the picker?

Upvotes: 1

Views: 300

Answers (1)

Roman Kolomenskii
Roman Kolomenskii

Reputation: 648

Create custom NumberPicker and override addView methods:

@Override
    public void addView(View child) {
        super.addView(child);
        updateView(child);
    }

    @Override
    public void addView(View child, int index, android.view.ViewGroup.LayoutParams params) {
        super.addView(child, index, params);
        updateView(child);
    }

    @Override
    public void addView(View child, android.view.ViewGroup.LayoutParams params) {
        super.addView(child, params);
        updateView(child);
    }

    private void updateView(View view) {
        if(view instanceof TextView){
            your_spanned_string = ...;
            ((TextView) view).setText(your_spanned_string);
        }
    }

Upvotes: 1

Related Questions