I have a vertical linear layout with a 2 views inside.
how can i center this view vertically? what's the most cost efficient
1) replace the linear layout with relative layout and use android:center_toparent= true
(expensive as two layout pass on every render)
2) put two place holder views one as first and last child. eachi with height = 0
and weight = 1
so the left space is spread equally.
can i make these dummy views as visibility = invisible
? it saves some cost?
Unless your activity is going to have a lot (say, hundreds or thousands) of these views, it is extremely unlikely that a single extra layout pass or two extra spacer views will make any noticeable difference. Personally, I wouldn't even bother measuring which of these strategies is fastest; I would just do whatever is standard on my team or whatever I'm used to doing.
Saving three nanoseconds doesn't help your users in any way. Writing code that you'll be able to come back to in six months and understand immediately will help you or your teammates immensely.
My gut reaction for the "best" way to do this (in terms of long-term maintainability) is to use the android:gravity
attribute on your LinearLayout. No need for spacer views.
<?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"
android:orientation="vertical">
<View
android:layout_width="match_parent"
android:layout_height="96dp"
android:background="#caf"/>
<View
android:layout_width="match_parent"
android:layout_height="96dp"
android:background="#fac"/>
</LinearLayout>