Question

I am new to Android development. I want every activity has a same customized popup menu on the top right. I use a LinearLayout in xxmenu.xml and include it in each activity's layout xml files. The display is OK. As the OnClickListener should be same, I don't want to implement the OnClick functions in every activity's Java file. How can I do this?

I know Android has inherent menu solution via OptionsMenu, but I don't know if it can be customized or how (e.g., I want it on topright corner, with different backgrounds, each item has an image icon followed by texts, one-side shadow, etc.)

Was it helpful?

Solution 2

First, the solution is to define a base class (e.g., BaseActivity) to extend Activity, and the actual activities using this menu to extend BaseActivity (e.g., MainActivity extends BaseActivity).

Second, use a separate xml to define the menu layout and include it in other layouts. A simple way to bind the listeners is to use android:onClick="toggleMenu".

Third, implement public void toggleMenu(View v) in BaseActivity.

We can also call the views and do the bindings in Java code. But I met a code sequence problem that if I get the clickable view via findViewById in BaseActivity's onCreate(), it returns null, and the binding fails. So the finding of the views and following bindings should be done in the child classes (e.g., MainActivity), after calling super.onCreate().

OTHER TIPS

Make an abstract BaseActivity class that implements onCreateOptionsMenu and onOptionsItemSelected for your common menu and menu items. Then make all your other activities extend from that one.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top