โดยปกติเมื่อเราใช้งานเริ่มต้นของ bottomNavigationView บน android เมื่อรันแล้วจะได้ผลดังนี้
จะสังเกตเห็นว่าที่ icon จะมีระยะห่างระหว่างตัวที่ active กับตัวที่ไม่ได้ active เมื่อกดย้ายไปแท็บใหม่ก็จะเลื่อนไปเป็นลักษณะเดิม วิธีแก้ไขคือ ให้ทำการปิด shift mode โดยมีวิธีการดังนี้ ให้สร้างคลาสใหม่ BottomNavigationViewHelper โดยมีโค้ดดังนี้
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
class BottomNavigationViewHelper { static void removeShiftMode(BottomNavigationView view) { BottomNavigationMenuView menuView = (BottomNavigationMenuView) view.getChildAt(0); try { Field shiftingMode = menuView.getClass().getDeclaredField("mShiftingMode"); shiftingMode.setAccessible(true); shiftingMode.setBoolean(menuView, false); shiftingMode.setAccessible(false); for (int i = 0; i < menuView.getChildCount(); i++) { BottomNavigationItemView item = (BottomNavigationItemView) menuView.getChildAt(i); item.setShiftingMode(false); // set once again checked value, so view will be updated item.setChecked(item.getItemData().isChecked()); } } catch (NoSuchFieldException e) { Log.e("ERROR NO SUCH FIELD", "Unable to get shift mode field"); } catch (IllegalAccessException e) { Log.e("ERROR ILLEGAL ALG", "Unable to change value of shift mode"); } } } |
จากนั้นให้เรียกใช้งาน
1 2 |
BottomNavigationView bottomNavigationView = (BottomNavigationView) findViewById(R.id.bottom_navigation); BottomNavigationViewHelper.removeShiftMode(bottomNavigationView); |
จากนั้นลองรันดูผลครับ
ผลที่ได้จะเป็นไปตามที่เราต้องการครับ โชคดีครับ
0