TD;DR
The view width must be exactly the half of the screen, and be centered. Using ConstraintLayout.
Note that the view does not have any inner width.
<View android:background="#ff0000" ... />
Original question
I would like to achieve a layout where a view size is half the screen size, and centered horizontally.
Something like this: |--view--|
I can't find any way using ConstraintLayout. The best i found is by using app:layout_constraintHorizontal_weight="1"
on 2 fake views positioned at the full left and full right respectively, and app:layout_constraintHorizontal_weight="1.5"
on my view.
Any better way ?
Result
What you have to do is:
Just add this in your XML
And this in your java.
First import these.
Then add these lines in onCreate function of your java file.
You can also set the Height using this method. And Yes, this View uses half the screen width whatever the screen size is.
As you don't want to do it via java. Add this to your XML.
By selecting this, move this guideline to end of the screen and note this value
app:layout_constraintGuide_begin="411dp"
. Now whatever the value is this is your screen's width.Add
marginStart
andmarginEnd
to your view as 411/4 dp. (calculate this value, XML is not going to do that).This will make your view in center with half width as parent.
Remember not every screen with is 411dp. This will not work for every phone's screen size out there.
With the beta release you can use percentage widths. If you cannot use the beta release, you can employ two vertical guidelines: one at 25% of the screen width and one at 75% of the width. The view with a width of
0dp
would be constrained between these two guidelines. This setup will give you a view that is 1/2 of the screen width and also centered.The following XML demonstrates both ways; one using the
ConstraintLayout
beta release and the second using features available in the current production release.XML Layout
As of "ConstraintLayout1.1.0-beta1" you can use percent to define widths & heights.
This will define the with to be 40% of the width of the screen. A combination of this and guidelines in percent allow you to create any percent based layout you want.
try this vertically divide
With ConstraintLayout, you can center a view in the screen like this:
Update your gradle to the last version of ConstraintLayout: