Hayk Abelyan
Hayk Abelyan

Reputation: 326

Center Gravity for TextView doesn't work on xxhdpi in RelativeLayout

I have TextViews with square background with numbers that appear every second. I use a square image for background and set the text gravity center to center the numbers in the squares. It doesn't work on xxhdpi phones. How I can center the numbers?

enter image description here

This is the code:

displayingCell = new TextView(MyActivity.this);
displayingCell.setTypeface(null, Typeface.BOLD);
displayingCell.setTextSize(mySize);
displayingCell.setTextColor(Color.BLACK);
displayingCell.setGravity(Gravity.CENTER);
displayingLayoutParam = new RelativeLayout.LayoutParams(diameter, diameter);
displayingLayoutParam.setMargins(marginLeft, marginTop, 0, 0);
displayingCell.setLayoutParams(displayingLayoutParam);
displayingCell.setBackground(myImage);
displayingCell.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);

Upvotes: 0

Views: 79

Answers (2)

Sagar Chavada
Sagar Chavada

Reputation: 5269

if this problem only appear on xxhdpi device.. than you can check it runtime for device and set marginbottom to text like this. i am adding margin to my toolbar text. hope you will get this trick

switch (getResources().getDisplayMetrics().densityDpi) {
            case DisplayMetrics.DENSITY_HIGH:
                Log.d("density:", "high");
                toolbar.setTitleMarginStart(160);
                break;
            case DisplayMetrics.DENSITY_XHIGH:
                // ...
                Log.d("density:", "xhigh");
                toolbar.setTitleMarginStart(200);
                break;
            case DisplayMetrics.DENSITY_XXHIGH:
                Log.d("density:", "xxhigh");
                toolbar.setTitleMarginStart(380);
                break;
        }

Upvotes: 0

Prexx
Prexx

Reputation: 2979

Try to remove

displayingLayoutParam.setMargins

and add

displayingLayoutParam.addRule(RelativeLayout.CENTER_IN_PARENT, RelativeLayout.TRUE);

Upvotes: 1

Related Questions