简体   繁体   中英

ActionBar with custom layout with custom menu item

I want to make custom action bar by put ImageView in the middle and have another icon with some info on the right side of actionbar like this:

I can make imageview in the middle already but problem is

  • when i inflate layout in onCreateOptionMenu() and set showAsAction="always" the view on the right take all space of action bar like this

but if i set it to "never" the middle image will show but menu item will gone

here is my code :

private void setActionBar(){
        actionBar = getActionBar();
        actionBar.setHomeButtonEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        actionBar.setDisplayUseLogoEnabled(true);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setDisplayOptions(ActionBar.DISPLAY_SHOW_CUSTOM | ActionBar.DISPLAY_SHOW_HOME);

        LayoutInflater linflater = (LayoutInflater) getSystemService(LAYOUT_INFLATER_SERVICE);
        View view = linflater.inflate(R.layout.actionbar_layout, null);
        ActionBar.LayoutParams lp = new ActionBar.LayoutParams(
                ActionBar.LayoutParams.WRAP_CONTENT,
                ActionBar.LayoutParams.WRAP_CONTENT);
        lp.gravity = Gravity.CENTER_HORIZONTAL | Gravity.CENTER_VERTICAL;
        view.setLayoutParams(lp);
        actionBar.setCustomView(view);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        MenuInflater menuInflater = getMenuInflater();
        menuInflater.inflate(R.menu.actionbar_right_icon, menu);
        MenuItem menuItem = menu.findItem(R.id.user_info);

        View rightIcon = menuItem.getActionView();
        RelativeLayout rightIconLayout = (RelativeLayout) rightIcon.findViewById(R.id.actionbar_right_icon);
        TextView user = (TextView) rightIconLayout.findViewById(R.id.actionbar_user);
        TextView id = (TextView) rightIconLayout.findViewById(R.id.actionbar_id);

        user.setText("User:test");
        id.setText("ID:xxxxx");

        return true;
    }

menu/actionbar_right_icon

<menu xmlns:android="http://schemas.android.com/apk/res/android" 
    >
    <item 
        android:id="@+id/user_info"
        android:actionLayout="@layout/actionbar_right_icon_layout"
        android:icon="@drawable/user_icon"
        android:showAsAction="always"

        />
</menu>

how can i fix this?

thank you in advance

ActionBar has customView support. Do not use onCreateOptionsMenu() and R.menu.actionbar_right_icon . Instead create a layout that takes all of the views you have draw.

You can do it like below

LayoutParams layout_params = new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT);
getSupportActionBar().setCustomView(custom_view, layout_params); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM