2013-04-24 3 views
21

Я хочу установить поля в процентах. У меня есть 4 изображения в линейном режиме и вы хотите установить по умолчанию левый, правый, верхний и нижний поля, которые сохраняют одинаковый процент для каждого размера экрана.Карточки макета андроида с процентом

Возможно ли это?

здесь демо, что я хочу .. enter image description here

И вот что я пробовал и не работает

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1" 
     android:weightSum="10" > 

     <Thumbnail 
      android:id="@+id/thumb1" 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="4" /> 

     <Thumbnail 
      android:id="@+id/thumb2" 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="4" /> 

    </LinearLayout> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:layout_weight="1" 
     android:weightSum="10" > 

     <Thumbnail 
      android:id="@+id/thumb3" 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="4" > 
     </Thumbnail> 

     <Thumbnail 
      android:id="@+id/thumb4" 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight="4" /> 

    </LinearLayout> 

</LinearLayout> 

Спасибо за вашу помощь

ответ

22

Вы можете иметь невидимый View s в вашем LinearLayout s в качестве прокладок и использовать механизм layout_weight, чтобы присвоить им относительный размер.

Пример:

<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_weight="1"> 

    <Thumbnail 
     android:id="@+id/thumb1" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="4" /> 

    <View 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:layout_weight="2" 
     android:visibility="invisible"/> 

    <Thumbnail 
     android:id="@+id/thumb2" 
     android:layout_width="0dp" 
     android:layout_height="match_parent" 
     android:layout_weight="4" /> 

</LinearLayout> 
+1

логично, если нет никакого другого пути :), но не уверен, что с использованием памяти, потому что мне нужно так много невидимых просмотров – dracula

+2

Существует '' вид для этого. Я не думаю, что при использовании невидимого 'View' будет штраф за производительность/память, но на самом деле не уверен -' View.java' огромен, снял его всего несколько минут. –

+1

@ Александр Малахов «Космос» был добавлен в уровень API 14, поэтому он не так полезен. Однако его назначение делает эту задачу более очевидной. – laalto

0

Глядя на ваше изображение здесь то, что вы могли бы сделать, использовать относительный макет и поставить линейную компоновку внутри него. вы также можете использовать weightSum, если хотите, чтобы изображения выглядели правильно.

<RelativeLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:layout_marginLeft="5dp" 
    android:layout_marginLeft="5dp" > 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentLeft="true" 
     android:orientation="vertical" > 

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 
    </LinearLayout> 

    <LinearLayout 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:layout_alignParentRight="true" 
     android:orientation="vertical" > 

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 

     <ImageView 
      android:layout_width="wrap_content" 
      android:layout_height="wrap_content" /> 
    </LinearLayout> 

</RelativeLayout> 
+0

, дающий точный запас, не является хорошим способом для нескольких экранов. поэтому я ищу решение для процентных ставок. – dracula

+0

Установка полей слева и справа для вашего относительного расположения задает одинаковые поля на всех экранах, так как эти значения находятся в dp. – deepdroid

+0

, но значения значений dp различны для каждой плотности. – dracula

19

Добавлено 1 августа 2017 года:

Два макеты из этого ответа в настоящее время устарели, но есть описание при условии о том, как получить ту же функциональность с ConstraintLayout. Благодаря dpg для указания этого.

Если вы планируете использовать проценты с ресурсами, this answer может быть вам полезна.


Старый ответ:

Существует в настоящее время лучший способ, который вышел с библиотекой поддержки версии 23.0.0 (о времени, не так ли?). Теперь вы можете использовать PercentFrameLayout или PercentRelativeLayout. Они оба имеют следующие атрибуты:

  • layout_widthPercent
  • layout_heightPercent
  • layout_marginPercent
  • layout_marginLeftPercent
  • layout_marginTopPercent
  • layout_marginRightPercent
  • layout_marginBottomPercent
  • layout_marginStartPe rcent
  • layout_marginEndPercent

Вы также можете посмотреть на PercentLayoutHelper.PercentLayoutParams

+0

Это только для Android 6? –

+1

Процентные макеты находятся в библиотеке поддержки процентов, а это значит, что они предназначены не только для Android 6. – neits

+1

Новый лучший способ стал устаревшим. Для обоих макетов по ссылкам: 'Этот класс устарел на уровне API 26.0.0-beta1. рассмотрите вместо этого использование ConstraintLayout и связанных макетов. « – dpg

0

Вы можете установить поля с использованием процентной ConstraintLayout's Guidelines.

Допустим, вы хотите, чтобы определить следующие процентные значения для макета:

Requested percentage values

Тогда вы просто добавьте следующие директивы в макете:

Layout Editor

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

    <ImageView 
     android:id="@+id/imageView1" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:scaleType="centerCrop" 
     app:srcCompat="@drawable/ic_launcher_background" 
     app:layout_constraintTop_toTopOf="@+id/horGuideline1" 
     app:layout_constraintStart_toStartOf="@+id/verGuideline1" 
     app:layout_constraintEnd_toStartOf="@+id/verGuideline2" 
     app:layout_constraintBottom_toTopOf="@+id/horGuideline2" /> 

    <ImageView 
     android:id="@+id/imageView2" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:scaleType="centerCrop" 
     app:srcCompat="@drawable/ic_launcher_background" 
     app:layout_constraintTop_toTopOf="@+id/horGuideline1" 
     app:layout_constraintStart_toStartOf="@+id/verGuideline3" 
     app:layout_constraintEnd_toStartOf="@+id/verGuideline4" 
     app:layout_constraintBottom_toTopOf="@+id/horGuideline2" /> 

    <ImageView 
     android:id="@+id/imageView3" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:scaleType="centerCrop" 
     app:srcCompat="@drawable/ic_launcher_background" 
     app:layout_constraintTop_toTopOf="@+id/horGuideline3" 
     app:layout_constraintStart_toStartOf="@+id/verGuideline1" 
     app:layout_constraintEnd_toStartOf="@+id/verGuideline2" 
     app:layout_constraintBottom_toTopOf="@+id/horGuideline4" /> 

    <ImageView 
     android:id="@+id/imageView4" 
     android:layout_width="0dp" 
     android:layout_height="0dp" 
     android:scaleType="centerCrop" 
     app:srcCompat="@drawable/ic_launcher_background" 
     app:layout_constraintTop_toTopOf="@+id/horGuideline3" 
     app:layout_constraintStart_toStartOf="@+id/verGuideline3" 
     app:layout_constraintEnd_toStartOf="@+id/verGuideline4" 
     app:layout_constraintBottom_toTopOf="@+id/horGuideline4" /> 

    <android.support.constraint.Guideline 
     android:id="@+id/verGuideline1" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     app:layout_constraintGuide_percent="0.05" /> 

    <android.support.constraint.Guideline 
     android:id="@+id/verGuideline2" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     app:layout_constraintGuide_percent="0.35" /> 

    <android.support.constraint.Guideline 
     android:id="@+id/verGuideline3" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     app:layout_constraintGuide_percent="0.65" /> 

    <android.support.constraint.Guideline 
     android:id="@+id/verGuideline4" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     app:layout_constraintGuide_percent="0.95" /> 

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

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

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

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

</android.support.constraint.ConstraintLayout> 

В результате ваш макет выглядит примерно так:

Result view

Смежные вопросы