我是Android开发的新手。我想在Xml中设置边距和内边距,但不要用dp或px,而是用百分比。有没有办法做到这一点?
虽然不可能,但是您可以在Java代码中通过以下方式获取屏幕的宽度和高度:
Display display = getWindowManager().getDefaultDisplay();
int width = display.getWidth();
int height = display.getHeight();
margin: 值px;
setmargin(int x) //method of view/layout.
通过这种方式,您可以根据屏幕大小而不是固定设置边距,基本上就像从Java代码中设置百分比一样。
<?xml version="1.0" encoding="utf-8"?>
<android.support.constraint.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:layout_width="match_parent"
android:layout_height="match_parent">
<TextView
android:id="@+id/textView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="TextView"
app:layout_constraintLeft_toLeftOf="@+id/guideline1"
app:layout_constraintTop_toTopOf="@+id/guideline2" />
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline1"
android:orientation="vertical"
app:layout_constraintGuide_percent="0.6" />
<android.support.constraint.Guideline
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="@+id/guideline2"
android:orientation="horizontal"
app:layout_constraintGuide_percent="0.25" />
</android.support.constraint.ConstraintLayout>
虽然已经很晚了,但是可以使用Android的百分比相对布局https://developer.android.com/reference/android/support/percent/PercentRelativeLayout.html。可以在某些属性中使用百分比,但并非所有属性都支持。例如,填充仍不支持百分比,而边距则支持。