3

Я хотел бы, чтобы это: а ViewPager наложенного на 2 стрелкиширина набора и высота в процентах относительной макете

enter image description here

И я получаю то, что я хочу этот код. Тем не менее, я получил эти предупреждения ворса:

  • эта схема бесполезна (для макетов)
  • вложенных весов плохо для производительности.

Интересно, есть ли лучший способ получить этот интерфейс, как я хочу.

<?xml version="1.0" encoding="utf-8"?> 
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
android:layout_width="match_parent" 
android:layout_height="match_parent" > 

<android.support.v4.view.ViewPager 
    android:id="@+id/dialog_instruction_pager" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" > 
</android.support.v4.view.ViewPager> 

<!-- this LinearLayout overlays the ViewPager --> 
<LinearLayout 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:gravity="center" 
    android:orientation="vertical" > 

    <!-- This is just the container for the left and right arrows , it is allocated with only 20% of screen height--> 
    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="0dp" 
     android:layout_weight=".2" 
     android:orientation="horizontal" > 

     <!-- I want to align this to the left and set width only 5% of the parent --> 
     <ImageButton 
      android:id="@+id/instruction_dialog_left_arrow" 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight=".05" 
      android:background="?android:attr/selectableItemBackground" 
      android:scaleType="fitCenter" 
      android:src="@drawable/arrow_left_grey" /> 

     <!-- This is the dummy layout, standing in the middle of 2 arrows so they can be align to the left and right of the parent --> 
     <LinearLayout 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight=".8" > 
     </LinearLayout> 

     <!-- I want to align this to the right and set width only 5% of the parent--> 
     <ImageButton 
      android:id="@+id/instruction_dialog_right_arrow" 
      android:layout_width="0dp" 
      android:layout_height="match_parent" 
      android:layout_weight=".05" 
      android:background="?android:attr/selectableItemBackground" 
      android:scaleType="fitCenter" 
      android:src="@drawable/arrow_right_grey" /> 
    </LinearLayout> 
</LinearLayout> 

P.S: Есть ли макет, который позволяет выравнивать детей слева, справа, снизу (как RelativeLayout), а также позволяет установить ширину, высоту в процентах (как атрибут «вес» в LinearLayout)?

Спасибо!

ответ

1
Try the below code and see whether it works, 
This code will get the layout what you have attached 

     <?xml version="1.0" encoding="utf-8"?> 
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent" 
    android:orientation="vertical" > 

    <android.support.v4.view.ViewPager 
    android:id="@+id/dialog_instruction_pager" 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:background="@color/theme_blue" > 
</android.support.v4.view.ViewPager> 

<ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentLeft="true" 
    android:layout_centerInParent="true" 
    android:background="@drawable/ic_launcher" /> 

    <ImageView 
    android:layout_width="wrap_content" 
    android:layout_height="wrap_content" 
    android:layout_alignParentRight="true" 
    android:layout_centerInParent="true" 
    android:background="@drawable/ic_launcher" /> 

</RelativeLayout> 
+0

Спасибо за ваш ответ, код, который вы предложили s не устанавливать ширину и высоту ImageView, а просто «wrap_content».Я хотел бы установить ширину и высоту изображения в процентах и ​​независимо от размеров изображения. –

+0

Но почему вы хотите установить ширину и высоту в процентах? По умолчанию размер содержимого будет равен размеру изображения. поместите изображение во все соответствующие чертежи в соответствии с коэффициентом масштабирования. Thats стандарт, предложенный android –

+0

Большое спасибо за ваше терпение, объяснив мне :), действительно ценю это. Я делаю демонстрационный проект, я загружаю и использую изображения с различными размерами из Интернета. Некоторые изображения, если я использую их с оберткой, будут слишком большими на экране. Я не знаю, что вы подразумеваете под «поместите изображение во все соответствующие чертежи в соответствии с коэффициентом масштабирования», можете ли вы быть более конкретным или отправить мне ссылку об этом? Большое спасибо! –

0

Попробуйте использовать RelativeLayout, а затем установить левое изображение на alignParentLeft и правильное изображение для alignParentRight

+0

Спасибо, но это не помогает установить ширину и высоту изображения. –

2

попробовать это

избежать эта схема бесполезна (для макетов) и должны android:background="@android:color/transparent" и добавить фиктивный вид в этом линейном макете, потому что макет не должен быть пустым.

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

и добавил родительский компоновщик для imageview, чтобы сделать изображение по вертикали центр

попробуйте этот код

<?xml version="1.0" encoding="utf-8"?> 
    <FrameLayout xmlns:android="http://schemas.android.com/apk/res/android" 
    android:layout_width="match_parent" 
    android:layout_height="match_parent"> 

    <android.support.v4.view.ViewPager 
     android:id="@+id/dialog_instruction_pager" 
     android:layout_width="wrap_content" 
     android:layout_height="wrap_content"></android.support.v4.view.ViewPager> 

    <!-- this LinearLayout overlays the ViewPager --> 
    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:gravity="center" 
     android:orientation="vertical"> 

     <!-- This is just the container for the left and right arrows , it is allocated with only 20% of screen height--> 
     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="0dp" 
      android:layout_weight=".2" 
      android:orientation="horizontal"> 
      <!--child layout to avoid nested weight with `waighSum` property--> 
      <LinearLayout 
       android:layout_width="match_parent" 
       android:layout_height="match_parent" 
       android:orientation="horizontal" 
       android:weightSum="100"> 

       <LinearLayout 
        android:layout_width="0dp" 
        android:layout_height="match_parent" 
        android:layout_weight="5" 
        android:gravity="center_vertical" 
        android:orientation="horizontal"> 
        <!-- I want to align this to the left and set width only 5% of the parent --> 
        <ImageButton 
         android:id="@+id/instruction_dialog_left_arrow" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:background="?android:attr/selectableItemBackground" 
         android:scaleType="fitCenter" 
         android:src="@drawable/icon_clock" /> 
       </LinearLayout> 
       <!-- This is the dummy layout, standing in the middle of 2 arrows so they can be align to the left and right of the parent --> 
       <LinearLayout 
        android:layout_width="0dp" 
        android:layout_height="match_parent" 
        android:layout_weight="90" 
        android:background="@android:color/transparent">// this line also makes layout usefull 
        <!-- dummy view becouse layout should not be empty --> 
        <View 
         android:layout_width="match_parent" 
         android:layout_height="match_parent" /> 
       </LinearLayout> 

       <LinearLayout 
        android:layout_width="0dp" 
        android:layout_height="match_parent" 
        android:layout_weight="5" 
        android:gravity="center_vertical" 
        android:orientation="horizontal"> 
        <!-- I want to align this to the right and set width only 5% of the parent--> 
        <ImageButton 
         android:id="@+id/instruction_dialog_right_arrow" 
         android:layout_width="match_parent" 
         android:layout_height="wrap_content" 
         android:background="?android:attr/selectableItemBackground" 
         android:scaleType="fitCenter" 
         android:src="@drawable/icon_clock" /> 
       </LinearLayout> 
      </LinearLayout> 
     </LinearLayout> 
    </LinearLayout> 
</FrameLayout> 

надеюсь, что он работает у

+0

Благодарим вас за ответ, он удаляет все предупреждения от Lint. Однако мне кажется, что этот xml имеет много вложенных макетов. Это замедляет работу? –

+0

no its not effects performance .. oly effects при добавлении ur с 10 последовательными вложенными макетами и более 80 просмотров в одном макете xml-файла. –

+0

Спасибо за ваше объяснение, я узнал от вас некоторые интересные вещи. –

2

Google представил новый API под названием android.support.percent

1) PercentRelativeLayout

2) PercentFrameLayout

Добавить компилировать зависимость как

compile 'com.android.support:percent:23.1.1' 

Вы можете указать размер в процентах, так получить как преимущество RelativeLayout и процент

<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"/> 
    <TextView 
     app:layout_widthPercent="40%" 
     app:layout_heightPercent="40%" 
     app:layout_marginTopPercent="15%" 
     app:layout_marginLeftPercent="15%"/> 
</android.support.percent.PercentRelativeLayout/> 
Смежные вопросы