简体   繁体   中英

Place image on the ActionBar on the center of the screen

I want to place company logo on the center of ActionBar (absolutely center of the screen). How can I calculate central point (by width) of the screen precisely?

Activity code:

ActionBar actionBar = getSupportActionBar();
        LayoutInflater inflator = (LayoutInflater) this
                .getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        View v = inflator.inflate(R.layout.action_bar_layout, null);
        actionBar.setDisplayShowTitleEnabled(false);
        actionBar.setDisplayShowCustomEnabled(true);
        actionBar.setCustomView(v);

action_bar_layout.xml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:gravity="center">

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

    <ImageView
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:src="@drawable/common_google_signin_btn_icon_dark_focused"/>

    <View
        android:layout_width="0dp"
        android:layout_height="wrap_content"
        android:layout_weight="1"/>

</LinearLayout>
  • I've placed this icon for example. 在此处输入图片说明

Have any ideas how to do this?

The Simple Answer is that you should use a RelativeLayout instead of LinearLayout and set android:layout_centerVertical="true" on the ImageView . Skip the two placeholder views.

I would Advise you to use a ToolBar instead though (Which requires you to use the support library). Place the RelativeLayout inside the ToolBar with width=height=match_parent. Then in your activity, do the following

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);

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