Android : How to show menu icon in Overflow menu
ความเดิมจากตอนที่แล้วเราสร้าง Overflow menu ขึ้นมาแล้ว แต่ไอคอนของเมนูไม่ตามมาด้วย ซึ่งเรามีทางแก้โดยเพิ่มโค้ดเข้าไปใน Java file ตอนสร้างเมนูด้วย onCreateOptionsMenu(Menu menu) ดังตัวอย่าง
@Override public boolean onCreateOptionsMenu(Menu menu) { getMenuInflater().inflate(R.menu.myMenu, menu); this.menu = menu; // ------------------------------------------------ //---- Add below to show icon menu in overflow ---- if(menu instanceof MenuBuilder){ MenuBuilder menuBuilder = (MenuBuilder) menu; menuBuilder.setOptionalIconsVisible(true); } // ------------------------------------------------ return super.onCreateOptionsMenu(menu); }
จากตัวอย่างข้างต้น เราเพิ่มโค้ด MenuBuilder เข้าไปครับ ก็จะทำให้ menu icon แสดงขึ้นมาใน Overflow menu
NOTE: แต่อีกสิ่งหนึ่งที่สำคัญคือ บน Overflow menu background color จะเป็นสีขาว เพราะฉะนั้นอย่าลืมกำหนดสีของ icon ไม่ใช่สีขาวครับ
NOTE2: การเพิ่มโค้ดนี้เข้าไปอาจทำให้เกิด Warning issue : RestrictedApi ดังตัวอย่าง
MenuBuilder.setOptionalIconsVisible can only be called from within the same library group (groupId=com.android.support) less… (⌘F1)
Inspection info:This API has been flagged with a restriction that has not been met. Examples of API restrictions:* Method can only be invoked by a subclass
* Method can only be accessed from within the same library (defined by the Gradle library group id)
* Method can only be accessed from tests. You can add your own API restrictions with the @RestrictTo annotation.
Issue id: RestrictedApi
แนวทางแก้ไข Warning นี้เราสามารถเพิ่ม @SuppressLint(“RestrictedApi”) ให้กับฟังก์ชัน onCreateOptionsMenu ได้ดังนี้
@SuppressLint("RestrictedApi") @Override public boolean onCreateOptionsMenu(Menu menu) { ... }