Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Set height of Toolbar half of attr/actionBarSize in xml

Is there anyway to set height of a "android.support.v7.widget.Toolbar" half of a predefined attr like "?android:attr/actionBarSize" in layout xml file? in fact I want the height of my toolbar be something like :

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height=("?android:attr/actionBarSize")/2
    >
like image 992
Mostafa Avatar asked Oct 18 '22 08:10

Mostafa


2 Answers

It is not possible to perform arithmetic actions in xml.

If you want to give the value through xml, then you have to perform following:

  1. in values/dimes.xml define a variable halfActionBar and make it be 28dp (original is 56dp).
  2. in values-land/dimes.xml define a variable halfActionBar and make it be 24dp (original is 48dp).
  3. in values-sw600dp-v13/dimes.xml define a variable halfActionBar and make it be 32dp (original is 64dp).

In your styles.xml theme.

<style name="AppTheme" parent="Theme.AppCompat.Light.NoActionBar">
    <item name="android:actionBarSize">@dimen/halfActionBar</item>
    ...
</style>

Then in your layout:

<android.support.v7.widget.Toolbar
    android:layout_width="match_parent"
    android:layout_height="?android:attr/actionBarSize"/>

Note, that this is a bad solution, because it depends on platform implementation. I advice to get actionBarSize from java/kotlin code (not from xml).

like image 140
azizbekian Avatar answered Oct 21 '22 08:10

azizbekian


You can't do it in XML but if you want to go with the programmatically way you can try with something like this, i took the idea from here

//themedContext is an Activity or a Context which has a Theme attached,
//you can't use Application context for this
final TypedArray array = themedContext.getTheme().obtainStyledAttributes(
                new int[] { android.R.attr.actionBarSize });
int actionBarSize = (int) array.getDimensionPixelSize(0, -1);
array.recycle();

Then to apply this to the Toolbar you could do:

Toolbar myToolbar = (Toolbar) findViewById(R.id.my_toolbar);

RelativeLayout.LayoutParams layoutParams = 
                 (RelativeLayout.LayoutParams) myToolbar.getLayoutParams();
//half the height of toolbar prior to set its value
layoutParams.height = (int)(actionBarSize / 2);
myToolbar.setLayoutParams(layoutParams);

setSupportActionBar(myToolbar);

PS: don't forget that this attribute value changes when the device is rotated, so you should set this custom value every time the device changes from portrait to landscape and viceversa.

like image 22
MatPag Avatar answered Oct 21 '22 08:10

MatPag