Использование разделителей на горизонтальном LinearLayout для предсотовых версий

Фон

Я пытаюсь использовать функцию делителей для linearLayout, даже на старых версиях Android.

для этого я обнаружил, что у actionBarSherlock есть хороший класс с именем " com.actionbarsherlock.internal.widget.IcsLinearLayout".

Эта проблема

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

когда Android использует API 17 и выше, а устройство использует язык RTL (например, иврит), и вы установили android:supportRtl="true" . это приводит к отображению некоторых разделителей (а некоторых нет), а также пустого разделителя (например, поля) слева.

Теперь я знаю, что внутренние представления не должны использоваться, но это очень важная функция для linearLayouts, и я не могу найти какую-либо хорошую альтернативу ей ( HoloEverywhere - очень тяжелая библиотека и недостаточно детализированная, чтобы ее можно было использовать для этот).

Вот пример использования:

activity_main.xml

<com.example.test.IcsLinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:divider="@drawable/divider"
    android:measureWithLargestChild="true"
    android:orientation="horizontal"
    android:showDividers="middle"
    tools:context=".MainActivity" >

    <View
        android:layout_width="0px"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#FFff0000" />

    <View
        android:layout_width="0px"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#FFffff00" />

    <View
        android:layout_width="0px"
        android:layout_height="wrap_content"
        android:layout_weight="1"
        android:background="#FFff00ff" />

</com.example.test.IcsLinearLayout>

divider.xml

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

    <size
        android:height="1dp"
        android:width="1dp" />

    <solid android:color="#FF000000" />

</shape>

Опять же, если он находится в вертикальной ориентации (и вы правильно установили ширину и высоту дочерних элементов), он прекрасно покажет разделители.

Что я пробовал

Я пытался заставить его игнорировать новые версии и применять только к старым (проверяя версии и избегая вызова новых функций API), но это не помогло.

Я также попытался скопировать часть drawDividersHor Horizontal из официального кода Android, как таковой:

  void drawDividersHorizontal(final Canvas canvas)
    {
    final int count=getChildCount();
    boolean isLayoutRtl=false;
    if(VERSION.SDK_INT>=VERSION_CODES.JELLY_BEAN_MR1)
      isLayoutRtl=(getLayoutDirection()&View.LAYOUT_DIRECTION_RTL)!=0;
    for(int i=0;i<count;i++)
      {
      final View child=getChildAt(i);
      if(child!=null&&child.getVisibility()!=GONE)
        if(hasDividerBeforeChildAt(i))
          {
          final LayoutParams lp=(LayoutParams)child.getLayoutParams();
          final int position;
          if(isLayoutRtl)
            position=child.getRight()+lp.rightMargin;
          else position=child.getLeft()-lp.leftMargin-mDividerWidth;
          drawVerticalDivider(canvas,position);
          }
      }
    if(hasDividerBeforeChildAt(count))
      {
      final View child=getChildAt(count-1);
      int position;
      if(child==null)
        {
        if(isLayoutRtl)
          position=getPaddingLeft();
        else position=getWidth()-getPaddingRight()-mDividerWidth;
        }
      else
        {
        final LayoutParams lp=(LayoutParams)child.getLayoutParams();
        if(isLayoutRtl)
          position=child.getLeft()-lp.leftMargin-mDividerWidth;
        else position=child.getRight()+lp.rightMargin;
        }
      drawVerticalDivider(canvas,position);
      }
    }

Вопрос

Как заставить это работать для горизонтальной ориентации тоже?

2 ответа

Попробуйте этот образец

<com.example.test.IcsLinearLayout 
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:divider="@drawable/divider"
android:measureWithLargestChild="true"
android:orientation="horizontal"
android:showDividers="middle"
tools:context=".MainActivity" >

 <View
android:layout_width="2dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="3dip"
android:background="#FFff0000" />
<View
android:layout_width="2dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="3dip"
android:background="#FFff0000" />
<View
android:layout_width="2dip"
android:layout_height="fill_parent"
android:layout_weight="1"
android:layout_margin="3dip"
android:background="#FFff0000" />
</com.example.test.IcsLinearLayout>

Вы можете просто сделать это (протестировано на телефоне Android api 10 (2.3.3 - 2.3.6)):

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
tools:context=".MainActivity" >

<View
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#FFff0000" />

<!-- First divider -->
<View
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:background="@android:color/black" />

<View
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#FFffff00" />

<!-- Second divider -->
<View
    android:layout_width="1dp"
    android:layout_height="wrap_content"
    android:background="@android:color/black" />

<View
    android:layout_width="0dp"
    android:layout_height="wrap_content"
    android:layout_weight="1"
    android:background="#FFff00ff" />

</LinearLayout>

Это обходной путь, но он работает!

Другие вопросы по тегам