I have a TextView inside a ConstraintLayout. Consider the TextView is 20dp high, and I want it to be at the top of the ConstraintLayout with a margin of 50dp. However, the ConstraintLayout's height is not fixed, and it is possible to be less than 70dp, meaning the TextView may not fit in there. In that case, I'd like to centralize the TextView vertically within the ConstraintLayout.
I tried the following layout:
<ConstraintLayout android:layout_height="match_parent">
<TextView
android:layout_height="20dp"
android:layout_marginTop="50dp"
android:layout_marginBottom="50dp"
app:layout_constraintVertical_bias="0.0"/>
</ConstraintLayout>
This layout works well when there's enough space in the ConstraintLayout to fit the TextView and the top margin. But when there's not, I'd need to change the vertical bias to 0.5 in order to centralize the TextView within the ConstraintLayout.
So is it possible to assign different biases (either in the XML or programatically) depending on whether there is or there isn't enough space to meet all the constraints? Otherwise, what other approach could be used?
Here's how to change the bias programmatically:
ConstraintSet set = new ConstraintSet();
ConstraintLayout constraintLayout = (ConstraintLayout)findViewById(R.id.your_layout);
set.clone(constraintLayout);
set.setVerticalBias(R.id.your_textview_id, 0.5f);
constraintSet.applyTo(constraintLayout);
and here's a way to detect your screen resolution and check for height restrictions:
private static String getScreenResolution(Context context) {
WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
Display display = wm.getDefaultDisplay();
DisplayMetrics metrics = new DisplayMetrics();
display.getMetrics(metrics);
int width = metrics.widthPixels;
int height = metrics.heightPixels;
return "{" + width + "," + height + "}";
}