Java – How do I use two different font sizes for button text in Android?

How do I use two different font sizes for button text in Android?… here is a solution to the problem.

How do I use two different font sizes for button text in Android?

How do I implement a button background for an ImageButton or Button with 2 TextViews, each using a different font size? I can’t use a static image as a background, I need to use xml or programmatically to achieve this.

This is a numeric keypad with a numeric value and a set of letters, each letter using a different font size that needs to be set as button text.

enter image description here

Here are some suggestions that pop into my head, but seem to have limitations because I want to reuse UI components and avoid code duplication.

  1. Create a layout XML with 2 text fields and set it as the background of the button. But how can I get references to these TextView fields to set their values in MyActivity.java?

  2. Using hierarchical lists? Again, textviews are referenced in the same problem

  3. Or create a custom View and inflate layout mentioned in step 1. This solution solved my problem.

Are there any other solutions for this UI requirement?

Thank you.

Solution

Hope this helps. This is certainly not the only solution, but it is a very simple one. Add XML sections instead of buttons in your XML.

XML

<LinearLayout
    android:id="@+id/button_layout"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:orientation="horizontal" >

<TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="20sp" 
        android:text="5"/>
    <TextView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:textSize="12sp" 
        android:text="ABC"/>

</LinearLayout>

Code

    LinearLayout button= (LinearLayout)findViewById(R.id.button_layout);
    button.setOnClickListener(new OnClickListener() {

@Override
        public void onClick(View v) {
             TODO DO whatever you want to do here

}
    });

Related Problems and Solutions