سؤال

I am trying to implement a button that will increase the font size of text in TextView I have came up with the following :

  Button biggerFont;
  TextView centerTextView;

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

    biggerFont =  (Button) findViewById(R.id.btn_bigger_font);
    centerTextView = (TextView) findViewById(R.id.textView_center);

    biggerFont.setOnClickListener(new OnClickListener() {
      @Override
      public void onClick(View v) {
        float tempSize = centerTextView.getTextSize();
        Log.d(USER_SERVICE, Float.toString(tempSize));
        centerTextView.setTextSize(++tempSize);
      }
    });
    // ...
  }

But this will increase the font size a lot! each time I click the button. On logging I have check and tempSize increases not by 1 but irregularly (44->90->182).

I have also tried using

    float tempSize = centerTextView.getTextSize() + 1;

but the same thing.

هل كانت مفيدة؟

المحلول

getTextSize()

the size (in pixels) of the default text size in this TextView.

use

setTextSize(TypedValue.COMPLEX_UNIT_PX, ++tempSize);

setTextSize uses scaled pixel by default (setTextSize(int)), with setTextSize(int, int) you say the unit to use.

نصائح أخرى

You are calling setTextSize(float size). According to the documentation, this sets the text size in scaled pixel units.

But then getTextSize() returns it back to you in pixel units, not scaled pixel units.

So the solution is to call the other setTextSize method that allows you to explicitly set the unit type.

Here's a stackoverflow question about the differences in units:

What's the relationship between pixels and scaled pixels

void setTextSize(int unit, float size) : 

Sets the default text size to a given unit and value

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top