Search code examples
javaandroidandroid-actionbar

How to get actionBar size properly programatically?


I need to shift a RecyclerView down by the size of my actionBar when a Button click occurs.

I tried this code

  params = (CoordinatorLayout.LayoutParams) myrv.getLayoutParams();

  public void changeRecyclerViewPosition() {
    params.setMargins(0, android.R.attr.actionBarSize, 0, 0);
    myrv.setLayoutParams(params);
}

And as a result the RecyclerView disapears when the Button is clicked.

So I tried to log the android.R.attr.actionBarSize value and it's too big (2130903043).

I thought that maybe the result is in pixels and it needs to be converted to dp.

So can you guys explain to me what's wrong and the reason behind that behaviour ?

EDIT:

  <android.support.design.widget.CoordinatorLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp"
tools:context=".Activities.LoadSavedCoffretDataActivity">


<android.support.design.widget.AppBarLayout
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:theme="@style/AppTheme.AppBarOverlay">

    <android.support.v7.widget.Toolbar
        android:id="@+id/toolbar"
        android:layout_width="match_parent"
        android:layout_height="?attr/actionBarSize"
        android:background="@android:color/white"
        app:popupTheme="@style/AppTheme.PopupOverlay" />

</android.support.design.widget.AppBarLayout>

<ImageView
    android:id="@+id/cancel_img"
    android:layout_marginTop="?attr/actionBarSize"
    android:elevation="5dp"
    android:layout_width="48dp"
    android:layout_height="48dp"
    android:src="@drawable/cancel" />

<android.support.v7.widget.RecyclerView
    android:id="@+id/recyclerview_id"
    android:layout_marginTop="?attr/actionBarSize"
    android:layout_width="match_parent"
    android:layout_height="match_parent">
</android.support.v7.widget.RecyclerView>

<LinearLayout
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_gravity="bottom|center_horizontal">

    <ImageView
        android:id="@+id/delete_img"
        android:layout_width="70dp"
        android:layout_height="70dp"
        android:src="@drawable/ic_delete_forever_black_24dp"/>

</LinearLayout>


Solution

  • You can get Action bar height by

    public void changeRecyclerViewPosition() {
    TypedValue tv = new TypedValue();
    int actionBarHeight = 0;
    if (getActivity().getTheme().resolveAttribute(R.attr.actionBarSize, tv, true))
    {
    actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data,getResources().getDisplayMetrics());
    }
    params.setMargins(0,actionBarHeight, 0, 0);
    myrv.setLayoutParams(params);
    }