2

I'm using this code, to get screen size

public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.some_layout);
    //more stuff
    setTextSize();
}

private void setTextSize() {
    DisplayMetrics metrics = new DisplayMetrics();
    getWindowManager().getDefaultDisplay().getMetrics(metrics);
    int width = metrics.widthPixels;
    //more code
    sometextview.setTextSize(TypedValue.COMPLEX_UNIT_PX, width/10); //example only
}

As it turns out, in rare cases this doesn't work. I'm setting some text size, and sometimes it doesn't resize text at all. I think it only happens whenever I haven't open application in a while, so it's very hard to debug it. Only idea I have is, that this is asking for screen size before application even knows it (it's the first activity). How can I solve this? This is the only method for getting screen resolution that I know that supports all APIs.

Cœur
  • 37,241
  • 25
  • 195
  • 267
Bojan Kogoj
  • 5,321
  • 3
  • 35
  • 57

1 Answers1

0

You need to use ViewTreeObserver for this specific Textview.

Some code snippet.

ViewTreeObserver vto = myTextView.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

            @Override
            public void onGlobalLayout() {
                setTextSize();

            }
        });

The only thing you should be careful of is that this would be called repeatedly every time view changes, so you need to keep a dirty flag to track changes.

PravinCG
  • 7,688
  • 3
  • 30
  • 55