Как использовать Percentage для макета Android?

Как мы можем использовать значения процент для элементов представления Android? что-то вроде этого

<TextView
        android:id="@+id/"
        android:layout_width="75%"
        android:layout_height="50%"/>

Ответ 1

До сих пор в библиотеке поддержки Android было ограничено, где это использовать:

  • с RelativeLayout

    android.support.percent.PercentRelativeLayout
    
  • с FrameLayout

    android.support.percent.PercentFrameLayout
    

Как его использовать?

Ну, сначала обязательно включите зависимость в build.grade(Module: app)

dependencies {
    compile 'com.android.support:percent:23.3.0'
}

Затем перейдите к вашему XML-макету в этом примере (.MainActivity)

<android.support.percent.PercentRelativeLayout

  xmlns:android="http://schemas.android.com/apk/res/android"
  xmlns:app="http://schemas.android.com/apk/res-auto"
  xmlns:tools="http://schemas.android.com/tools"
  android:layout_width="match_parent"
  android:layout_height="match_parent"
  android:paddingBottom="@dimen/activity_vertical_margin"
  android:paddingLeft="@dimen/activity_horizontal_margin"
  android:paddingRight="@dimen/activity_horizontal_margin"
  android:paddingTop="@dimen/activity_vertical_margin"
  tools:context=".MainActivity">


  <Button
    android:id="@+id/button"
    android:text="Button"
    android:layout_height="wrap_content"
    android:layout_alignParentTop="true"
    app:layout_widthPercent="30%"/>

  <Button    
    android:id="@+id/button2"
    android:text="Button 2"
    android:layout_height="wrap_content"
    android:layout_toRightOf="@id/button"
    app:layout_widthPercent="60%"/>

  <Button
    android:id="@+id/button3"
    android:text="Button 3"
    android:layout_height="wrap_content"
    android:layout_below="@+id/button"
    android:layout_alignParentStart="true"
    android:layout_alignParentLeft="true"
    app:layout_widthPercent="90%"/>

</android.support.percent.PercentRelativeLayout>

Подробнее см. здесь:

Ответ 2

В библиотеке поддержки добавлен процентный макет.

Это можно сделать так:

 <android.support.percent.PercentFrameLayout
     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.PercentFrameLayout>

https://developer.android.com/reference/android/support/percent/PercentFrameLayout.html

Ответ 3

Вы можете использовать PercentRelativeLayout, Это недавнее недокументированное дополнение к Библиотека поддержки дизайна, позволяет указывать не только элементы по отношению друг к другу, но и общий процент доступных пространство.

Структура

<android.support.percent.PercentRelativeLayout
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    >
    <ImageView
        android:id="@+id/imageview"
        android:layout_gravity="center"
        app:layout_widthPercent="50%"
        app:layout_heightPercent="50%"
        android:src="@mipmap/ic_launcher"
        android:background="#cecece"/>
    <TextView
        android:id="@+id/textview1"
        android:layout_below="@id/imageview"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        app:layout_marginStartPercent="25%"
        app:layout_marginEndPercent="25%"
        android:text="PercentRelativeLayout example"
        android:background="#bebebe"/>


</android.support.percent.PercentRelativeLayout>

Процентный пакет предоставляет API-интерфейсы для поддержки добавления и управления размерами, основанными на процентах, в вашем приложении.

Чтобы использовать эту библиотеку, вам нужно добавить эту библиотеку в список your Gradle dependency:

dependencies {
    compile 'com.android.support:percent:22.2.0'
    // or compile 'com.android.support:percent:23.1.0'
}

Для демонстрационной цели вы можете посетить Git android-percent-support-lib-sample.

Ответ 4

В Google появился новый API android.support.percent

Пример PercentRelativeLayout

 <android.support.percent.PercentFrameLayout
         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/myTextView"
         app:layout_widthPercent="75%"
         app:layout_heightPercent="50%"/>
 </android.support.percent.PercentFrameLayout>

Ответ 5

Вы можете использовать PercentRelativeLayout Это подкласс RelativeLayout, который поддерживает размеры и поля на основе процентов.

Чтобы использовать эту библиотеку, вы должны добавить эту библиотеку в свой Gradle dependency:

dependencies {
    compile 'com.android.support:percent:23.1.0'
}

Структура выборки

<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>

Ответ 6

При отключении PercentFrameLayout и PercentRelativeLayout в 26.0.0 вам нужно использовать ConstraintLayout для того, чтобы размер TextView имел процентные значения.

ConstraintLayout - действительно мощный инструмент для создания адаптивного интерфейса для платформы Android, вы можете найти более подробную информацию здесь Создайте отзывчивый интерфейс с помощью ConstraintLayout.

Вот пример того, как размер TextView (w = 75%, h = 50%) с помощью 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:id="@+id/ver_guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="vertical"
        app:layout_constraintGuide_percent="0.75"/>

    <android.support.constraint.Guideline
        android:id="@+id/hor_guideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.5"/>

    <TextView
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:layout_marginBottom="0dp"
        android:layout_marginEnd="0dp"
        android:layout_marginStart="0dp"
        android:layout_marginTop="0dp"
        app:layout_constraintBottom_toTopOf="@+id/hor_guideline"
        app:layout_constraintEnd_toStartOf="@+id/ver_guideline"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent" />

</android.support.constraint.ConstraintLayout>

Не забудьте добавить constraint-layout зависимость к вашему модулю build.gradle file

dependencies {
    ...
    implementation 'com.android.support.constraint:constraint-layout:1.0.2'
    ...
}

Или отредактируйте свой макет непосредственно в редакторе макетов, как показано ниже:

Редактор макета

В результате ваша ширина TextView составляет 75% от родительской ширины, а высота - 50% от родительской высоты:

Изображение-1

Изображение-2