Sharing menu bar between activities

2019-07-15 06:29发布

问题:

I have a menu bar on my app, that I need to share between 5 of my activities. My menu bar (= 5 buttons allowing to switch between activities) has exactly the same UI and the same behavior for any activity so I would like to share both menu bar XML view code and controller code.

I already found a way to share the XML code using Reusable UI Components but I can't find a way to share the controller code that controls the menu bar buttons clicks.

Note: my menu bar is a custom-made one, not the Android Options Menu one.

Thanks in advance.

回答1:

I think the best solution is to use Fragments, using the Android Support v4 library



回答2:

you can take one activity with you menu bar implemented simply, and then you can use that class to extend each of you activity instead of acivity

suppose your base activity looks as below: BaseActivity extends Activity

and after this you can extends all your five activity with BaseActivity



回答3:

Maybe you should try creating your own View class. Say the root tag of your menu bar is RelativeLayout.

public class MenubarView extends RelativeLayout {
    public MenubarView(Context context, AttributeSet attrs) {
        super(context, attrs);

        // inflates menubar.xml into this view
        // (note: menubar's root view should probably be a 'merge' tag)
        LayoutInflater.from(context).inflate(R.layout.menubar, this);
    }

    // controller code
}

Then in your xml, just embed your custom view like so:

<LinearLayout
   ... />

    <com.your.package.MenubarView
        ... />

</LinearLayout>