Browse Source

fix Android title centering bug (#4674)

Stanislav Doskalenko 5 years ago
parent
commit
4aa5cd17bf

+ 12
- 2
lib/android/app/src/main/java/com/reactnativenavigation/views/titlebar/TitleBar.java View File

@@ -29,6 +29,8 @@ public class TitleBar extends Toolbar {
29 29
 
30 30
     private TitleBarButtonController leftButtonController;
31 31
     private View component;
32
+    private Alignment mAlignment;
33
+    private CharSequence mTitle;
32 34
 
33 35
     public TitleBar(Context context) {
34 36
         super(context);
@@ -40,6 +42,10 @@ public class TitleBar extends Toolbar {
40 42
     public void setTitle(CharSequence title) {
41 43
         clearComponent();
42 44
         super.setTitle(title);
45
+        if (mTitle != title && mAlignment != null) {
46
+            this.setTitleAlignment(mAlignment);
47
+        }
48
+        mTitle = title;
43 49
     }
44 50
 
45 51
     public String getTitle() {
@@ -72,8 +78,9 @@ public class TitleBar extends Toolbar {
72 78
     }
73 79
 
74 80
     public void setTitleAlignment(Alignment alignment) {
81
+        mAlignment = alignment;
75 82
         TextView title = findTitleTextView();
76
-        if (title == null) return;
83
+        if (title == null || title == mTitle) return;
77 84
         alignTextView(alignment, title);
78 85
     }
79 86
 
@@ -94,9 +101,12 @@ public class TitleBar extends Toolbar {
94 101
     }
95 102
 
96 103
     private void alignTextView(Alignment alignment, TextView view) {
104
+        int width = view.getResources().getDisplayMetrics().widthPixels;
97 105
         view.post(() -> {
98 106
             if (alignment == Alignment.Center) {
99
-                view.setX((getWidth() - view.getWidth()) / 2);
107
+                view.measure(0, 0);
108
+                //noinspection IntegerDivisionInFloatingPointContext
109
+                view.setX((width - view.getWidth()) / 2);
100 110
             } else if (leftButtonController != null) {
101 111
                 view.setX(getContentInsetStartWithNavigation());
102 112
             } else {