Creating a customised button with 2 lines of text

2019-08-01 02:33发布

问题:

I'm new to Android (Visual Studio for 20 years). I need to create a clickable control that features 2 lines of text (1 smaller font at the top of the button for a caption and a larger font line for a value - would post an image but I'm not allowed). The size of the larger font scales so that the value will fit on the control. I'm pretty sure I need to subclass the button control but not sure how to in this case. All samples I have found don't seem to fit the bill.

Have done this easily with VB.Net but I'm stumped when I try with Android. Any help very much appreciated. Might be a handy control for others too. Thanks

回答1:

You could try using Spannable in the code like:

public class Test extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        Button but = (Button) findViewById(R.id.button1);
        String butText= "Line 1\nLine 2";
        but.setText(formatString(butText));
    }

    private Spannable formatString(String str) {

        int startSpan = str.indexOf("\n");
        int endSpan   = str.length();
        Spannable spanString = null;
        spanString = new SpannableString(str);
        spanString.setSpan(new TextAppearanceSpan(this,
                R.style.custompoint), startSpan, endSpan,
                Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);        
        return spanString;
    }

}

Where you have a style 'custompoint'

<?xml version="1.0" encoding="utf-8"?>
<resources>
    <style
        name="custompoint">
        <item name="android:textSize">24sp</item>
        <item name="android:textStyle">bold</item>
    </style>
</resources>