将图像放在屏幕中央的ActionBar上

时间:2016-04-27 06:33:57

标签: java android user-interface android-actionbar

我想在ActionBar的中心放置公司徽标(绝对是屏幕的中心)。如何精确计算屏幕的中心点(按宽度)?

活动代码:

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>
  • 我已经放置了这个图标。 enter image description here

有任何想法如何做到这一点?

1 个答案:

答案 0 :(得分:0)

简单答案是,您应该使用RelativeLayout代替LinearLayout并在android:layout_centerVertical="true"上设置ImageView。跳过两个占位符视图。

我建议您使用ToolBar代替(这需要您使用支持库)。将RelativeLayout放在ToolBar中,width = height = match_parent。然后在您的活动中,执行以下操作

mToolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(mToolbar);
相关问题