Можно ли указывать размеры объектов в процентном соотношении от экрана?

74
07 марта 2021, 21:20

Можно ли указывать размеры (длина, ширина) различных объектов в процентном соотношении, в зависимости от размеров экрана (ну или от материнского объекта)?

Answer 1

Да, можно. Причём, несколькими способами.

  1. Рекомендуемый гуглом ConstraintLayout:

Первый способ:

<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">
     <Button
         android:text="Button"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:id="@+id/button"
         app:layout_constraintWidth_default="percent"
         app:layout_constraintWidth_percent=".4"/>
</android.support.constraint.ConstraintLayout>

Второй способ:

<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">
     <android.support.constraint.Guideline
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/left_guideline"
         app:layout_constraintGuide_percent=".15"
         android:orientation="vertical"/>
     <android.support.constraint.Guideline
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/right_guideline"
         app:layout_constraintGuide_percent=".85"
         android:orientation="vertical"/>
     <android.support.constraint.Guideline
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/top_guideline"
         app:layout_constraintGuide_percent=".15"
         android:orientation="horizontal"/>
     <android.support.constraint.Guideline
         android:layout_width="wrap_content"
         android:layout_height="wrap_content"
         android:id="@+id/bottom_guideline"
         app:layout_constraintGuide_percent=".85"
         android:orientation="horizontal"/>
     <Button
         android:text="Button"
         android:layout_width="0dp"
         android:layout_height="0dp"
         android:id="@+id/button"
         app:layout_constraintLeft_toLeftOf="@+id/left_guideline"
         app:layout_constraintRight_toRightOf="@+id/right_guideline"
         app:layout_constraintTop_toTopOf="@+id/top_guideline"
         app:layout_constraintBottom_toBottomOf="@+id/bottom_guideline" />
</android.support.constraint.ConstraintLayout>
  1. С использованием веса (при активном использовании во множестве вложенных элементов снижает производительность):

<LinearLayout
     xmlns:android="http://schemas.android.com/apk/res/android"
     android:layout_width="match_parent"
     android:layout_height="wrap_content">
     <Space
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:weight="1" />
     <Button
         android:text="Button"
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:id="@+id/button"
         android:weight="1" />
     <Space
         android:layout_width="0dp"
         android:layout_height="wrap_content"
         android:weight="1" />
</LinearLayout>
  1. Не рекомендованный и устаревший PercentRelativeLayout

<android.support.percent.PercentRelativeLayout
     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">
 <ImageView
     app:layout_widthPercent="50%"
     app:layout_heightPercent="50%"
     app:layout_marginTopPercent="25%"
     app:layout_marginLeftPercent="25%"/>
</android.support.percent.PercentRelativeLayout>
Answer 2

Работает для меня (программно):

 //Находим размеры экрана
 Display display = getWindowManager().getDefaultDisplay();
 Point size = new Point();
 display.getSize(size);
 int width = size.x;
 int height = size.y;
 //И назначаем нужные размеры
  YourObject.getLayoutParams().width = width * percent;
  YourObject.getLayoutParams().height = height * percent;
 //percent - Ваш процент
READ ALSO
Подскажите плагин Atom для языка JavaScript

Подскажите плагин Atom для языка JavaScript

пишу код на JS в текстовом редакторе atom, иногда бывает, что забываю как правильно пишутся некоторые функции/методы (например ObjectdefineProperty и тд),...

106
Почему оно не работает? [закрыт]

Почему оно не работает? [закрыт]

Хотите улучшить этот вопрос? Обновите вопрос так, чтобы он вписывался в тематику Stack Overflow на русском

123
SyntaxError: JSON.parse в Firefox 60 ESR, Debian

SyntaxError: JSON.parse в Firefox 60 ESR, Debian

При помощи fetch получаю данные из контроллераНа самом деле не важно какие, главное что возвращаются они в json

84
Помогите переписать код JQUERY на Javascript [закрыт]

Помогите переписать код JQUERY на Javascript [закрыт]

Хотите улучшить этот вопрос? Обновите вопрос так, чтобы он вписывался в тематику Stack Overflow на русском

89