Search code examples
androidandroid-layoutandroid-actionbar

How to add imageview on right hand side of action bar?


I want to add image view on action bar right hand side.I tried to do that but i couldn't. Can anyone help me?

This is my image view xml

 <ImageView
        android:id="@+id/imageView4"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentRight="true"
        android:layout_alignParentTop="true"
        android:src="@drawable/adnace_search_i" />

This is the image of action bar that i want to create.

enter image description here


Solution

  • Try the following code:

    ActionBar actionBar = getActionBar();
    actionBar.setDisplayOptions(actionBar.getDisplayOptions() |
            ActionBar.DISPLAY_SHOW_CUSTOM);
    ImageView imageView = new ImageView(actionBar.getThemedContext());
    imageView.setScaleType(ImageView.ScaleType.CENTER);
    imageView.setImageResource(R.drawable.adnace_search_i);
    ActionBar.LayoutParams layoutParams = new ActionBar.LayoutParams(
            ActionBar.LayoutParams.WRAP_CONTENT,
            ActionBar.LayoutParams.WRAP_CONTENT,
                    Gravity.RIGHT |
                    Gravity.CENTER_VERTICAL);
    layoutParams.rightMargin = 40;
    imageView.setLayoutParams(layoutParams);
    actionBar.setCustomView(imageView);