简体   繁体   中英

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?

在此处输入图片说明

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);

Try to remove

displayingLayoutParam.setMargins

and add

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

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;
        }

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM