Result
What you have to do is:
Just add this in your XML
<View
android:id="@+id/viewV1"
android:layout_height="match_parent"
android:background="#ff0000"
app:layout_constraintLeft_toLeftOf="parent"
app:layout_constraintRight_toRightOf="parent"
app:layout_constraintTop_toTopOf="parent"
app:layout_constraintBottom_toBottomOf="parent"
android:layout_width="match_parent"
/>
And this in your java.
First import these.
import android.graphics.Point;
import android.support.constraint.ConstraintLayout;
import android.view.Display;
import android.view.View;
Then add these lines in onCreate function of your java file.
Display display = getWindowManager().getDefaultDisplay();
Point size = new Point();
display.getSize(size);
int width1 = size.x;
//int height = size.y;
View v = findViewById(R.id.viewV1);
ConstraintLayout.MarginLayoutParams params = (ConstraintLayout.MarginLayoutParams) v.getLayoutParams();
params.width = width1/2; params.leftMargin = width1/4; params.rightMargin = width1/4;
v.setLayoutParams(params);
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.
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline5"
app:layout_constraintGuide_begin="411dp"
android:orientation="vertical"
/>
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
and marginEnd
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.