2016-08-25 2 views
4

Я пытаюсь создать транзакцию Master/Detail в одном фрагменте. Я думал об использовании LinearLayout в качестве контейнера моего edittext для моего заголовка. Затем нажмите RecyclerView для подробностей.Android: сворачивание Linearlayout вместо Collapsing Toolbar

Как реализовать свертывание/расширение LinearLayout, аналогичное эффекту CollapsingToolbar?

Вот скриншот того, что я пытаюсь сделать.

enter image description here

Мой XML-код до сих пор.

<?xml version="1.0" encoding="utf-8"?> 
<LinearLayout 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:orientation="vertical"> 

    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:orientation="vertical" 
     android:background="@color/colorAccent" 
     android:padding="@dimen/activity_horizontal_margin"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:src="@drawable/ic_date_range_black_24dp" 
       android:tint="@android:color/darker_gray" /> 

      <android.support.v4.widget.Space 
       android:layout_width="@dimen/activity_horizontal_margin" 
       android:layout_height="wrap_content" /> 

      <android.support.design.widget.TextInputLayout 
       android:id="@+id/date_til" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:hint="Date"> 

       <android.support.design.widget.TextInputEditText 
        android:id="@+id/date" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:cursorVisible="false" 
        android:focusable="false" 
        android:longClickable="false" /> 

      </android.support.design.widget.TextInputLayout> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:src="@drawable/ic_store_black_24dp" 
       android:tint="@android:color/darker_gray" /> 

      <android.support.v4.widget.Space 
       android:layout_width="@dimen/activity_horizontal_margin" 
       android:layout_height="wrap_content" /> 

      <android.support.design.widget.TextInputLayout 
       android:id="@+id/store_til" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:hint="Store"> 

       <android.support.design.widget.TextInputEditText 
        android:id="@+id/store" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" /> 

      </android.support.design.widget.TextInputLayout> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:src="@drawable/ic_place_black_24dp" 
       android:tint="@android:color/darker_gray" /> 

      <android.support.v4.widget.Space 
       android:layout_width="@dimen/activity_horizontal_margin" 
       android:layout_height="wrap_content" /> 

      <android.support.design.widget.TextInputLayout 
       android:id="@+id/location_til" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content"> 

       <android.support.design.widget.TextInputEditText 
        android:id="@+id/location" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:hint="Location" /> 

      </android.support.design.widget.TextInputLayout> 

     </LinearLayout> 

    </LinearLayout> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recycler" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:scrollbars="vertical" 
     app:layoutManager="LinearLayoutManager" 
     tools:listitem="@layout/list_car" /> 

</LinearLayout> 

Кроме того, не уверен, если это может быть сделано с CollapsingToolbar, так как я в основном видел только ImageView рушится на панели инструментов.

Примите любую помощь.

ОБНОВЛЕНИЕ: В принципе, я хочу сделать это, чтобы иметь возможность свернуть вид заголовка при прокрутке вверх. Затем разверните его при прокрутке вниз.

+0

обновите файл xml здесь –

+0

Добавлен xml-файл. – ank

ответ

3

Вы можете использовать таймер и постепенно уменьшить высоту/края topbar в LinearLayout (Edit: изъяны в ответ Антон Майоров в фиксирован)

enter image description here

см ниже фрагмент кода (проверено на устройствах)

подход I: ответ Антон Майоров, в изъяны фиксировано, это гораздо проще, чем 2-й реализации ниже

public class MainActivity extends AppCompatActivity { 

    LinearLayout toolbar; 
    int mOriginalHeight; 
    boolean initialSizeObtained = false;  
    boolean isShrink = false; 

    Animation _hideAnimation = new Animation() { 
     @Override 
     protected void applyTransformation(float interpolatedTime, Transformation t) { 
      LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) toolbar.getLayoutParams(); 
      params.topMargin = -(int) (mOriginalHeight * interpolatedTime); 
      toolbar.setLayoutParams(params); 
     } 
    }; 

    Animation _showAnimation = new Animation() { 
     @Override 
     protected void applyTransformation(float interpolatedTime, Transformation t) { 
      LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) toolbar.getLayoutParams(); 
      params.topMargin = (int) (mOriginalHeight * (interpolatedTime - 1)); 
      toolbar.setLayoutParams(params); 
     } 
    }; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     toolbar = (LinearLayout) findViewById(R.id.toolbar); 
     //Get the original height, which is measured according to WRAP_CONTENT 
     toolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
      @Override 
      public void onGlobalLayout() { 
       if (initialSizeObtained) 
        return; 
       initialSizeObtained = true; 
       mOriginalHeight = toolbar.getMeasuredHeight(); 
      } 
     }); 
     _hideAnimation.setDuration(2000); 
     _showAnimation.setDuration(2000); 
    } 

    //Click on the Olimpic image --> Toggles the top toolbar 
    public void ToggleTopBar(View view) { 
     isShrink = !isShrink; 

     toolbar.clearAnimation(); //Important    
     toolbar.startAnimation(isShrink? _hideAnimation : _showAnimation); 
    } 
} 

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

public class MainActivity extends AppCompatActivity { 

    LinearLayout toolbar; 
    int mOriginalHeight; 
    boolean initialSizeObtained = false; 
    int currentHeight; 
    boolean isShrink = false; 
    Timer timer; 

    @Override 
    protected void onCreate(Bundle savedInstanceState) { 
     super.onCreate(savedInstanceState); 
     setContentView(R.layout.activity_main); 

     toolbar = (LinearLayout) findViewById(R.id.toolbar); 
     toolbar.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { 
      @Override 
      public void onGlobalLayout() { 
       if (initialSizeObtained) 
        return; 
       initialSizeObtained = true; 
       mOriginalHeight = toolbar.getMeasuredHeight(); 
       currentHeight = mOriginalHeight; 
       Log.d("Demo", "Original height is " + mOriginalHeight); 
      } 
     }); 
    } 

    //Click on the Olimpic image --> Toggles the top toolbar 
    public void ToggleTopBar(View view) { 
     isShrink = !isShrink; 
     Resize(isShrink, toolbar, 250); 
    } 


    void Resize(final boolean isShrink, final LinearLayout layout, final int minHeight) { 
     final int H0 = mOriginalHeight; 
     timer = runTimerAction(10, new Runnable() { 
        public void run() { 
         Log.d("demo", "Current Height= " + currentHeight); 
         if (isShrink && currentHeight > minHeight) { 
          currentHeight -= 10; 
          layout.getLayoutParams().height = currentHeight; 
          refreshToolbar(); 
         } else if (!isShrink && currentHeight < H0) { 
          currentHeight += 10; 
          layout.getLayoutParams().height = currentHeight; 
          refreshToolbar(); 
         } else { 
          layout.getLayoutParams().height = isShrink ? minHeight : H0; 
          refreshToolbar(); 
          if (timer != null) 
           timer.cancel(); 
         } 
        } 
       } 
     ); 
    } 

    public void refreshToolbar() { 
     runOnUiThread(new Runnable() { 
      @Override 
      public void run() { 
       toolbar.requestLayout(); 
      } 
     }); 
    } 
+0

Как назвать эти анимации во время прокрутки? –

+0

Вы прочитали приведенный выше код и сможете его понять? – David

+0

Я могу понять подход 1, но это похоже на то, что анимация происходит, когда мы нажимаем на нее, возможно ли ее развернуть, когда мы прокручиваем вверх и ругаемся при прокрутке вниз? –

0

попробовать это я добавил координатор и CollapsingToolbarLayput

<?xml version="1.0" encoding="utf-8"?> 
<android.support.design.widget.CoordinatorLayout 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:fitsSystemWindows="true"> 

<android.support.design.widget.AppBarLayout 
    android:id="@+id/app_bar_layout" 
    android:layout_width="match_parent" 
    android:layout_height="wrap_content" 
    android:fitsSystemWindows="true"> 
    <android.support.design.widget.CollapsingToolbarLayout 
     android:id="@+id/collapsing_toolbar" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:fitsSystemWindows="true" 
     app:contentScrim="?attr/colorPrimary" 
     app:expandedTitleMarginEnd="64dp" 
     app:expandedTitleMarginStart="15dp" 
     app:layout_scrollFlags="scroll|exitUntilCollapsed"> 
    <LinearLayout 
     android:layout_width="match_parent" 
     android:layout_height="wrap_content" 
     android:background="@color/colorAccent" 
     android:orientation="vertical" 
     android:padding="@dimen/activity_horizontal_margin"> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:src="@drawable/ic_date_range_black_24dp" 
       android:tint="@android:color/darker_gray" /> 

      <android.support.v4.widget.Space 
       android:layout_width="@dimen/activity_horizontal_margin" 
       android:layout_height="wrap_content" /> 

      <android.support.design.widget.TextInputLayout 
       android:id="@+id/date_til" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:hint="Date"> 

       <android.support.design.widget.TextInputEditText 
        android:id="@+id/date" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:cursorVisible="false" 
        android:focusable="false" 
        android:longClickable="false" /> 

      </android.support.design.widget.TextInputLayout> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:src="@drawable/ic_store_black_24dp" 
       android:layout_gravity="center" 
       android:tint="@android:color/darker_gray" /> 

      <android.support.v4.widget.Space 
       android:layout_width="@dimen/activity_horizontal_margin" 
       android:layout_height="wrap_content" /> 

      <android.support.design.widget.TextInputLayout 
       android:id="@+id/store_til" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content" 
       android:hint="Store"> 

       <android.support.design.widget.TextInputEditText 
        android:id="@+id/store" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" /> 

      </android.support.design.widget.TextInputLayout> 

     </LinearLayout> 

     <LinearLayout 
      android:layout_width="match_parent" 
      android:layout_height="wrap_content" 
      android:orientation="horizontal"> 

      <ImageView 
       android:layout_width="wrap_content" 
       android:layout_height="wrap_content" 
       android:layout_gravity="center" 
       android:src="@drawable/ic_place_black_24dp" 
       android:tint="@android:color/darker_gray" /> 

      <android.support.v4.widget.Space 
       android:layout_width="@dimen/activity_horizontal_margin" 
       android:layout_height="wrap_content" /> 

      <android.support.design.widget.TextInputLayout 
       android:id="@+id/location_til" 
       android:layout_width="match_parent" 
       android:layout_height="wrap_content"> 

       <android.support.design.widget.TextInputEditText 
        android:id="@+id/location" 
        android:layout_width="match_parent" 
        android:layout_height="wrap_content" 
        android:hint="Location" /> 

      </android.support.design.widget.TextInputLayout> 

     </LinearLayout> 

    </LinearLayout> 
    </android.support.design.widget.CollapsingToolbarLayout> 
</android.support.design.widget.AppBarLayout> 

    <android.support.v7.widget.RecyclerView 
     android:id="@+id/recycler" 
     android:layout_width="match_parent" 
     android:layout_height="match_parent" 
     android:scrollbars="vertical" 
     app:layout_behavior="@string/appbar_scrolling_view_behavior" 
     tools:listitem="@layout/list_car" 
     app:layoutManager="LinearLayoutManager" /> 

Надеюсь, это поможет вам.

2

Улучшение моего ответа с помощью комментария Дэвида.

Я живой "TopMargin" вашего заголовка:

LinearLayout _headerLayout; // expected to be set in "onCreateView" 
int _headerHeight; // expected to be set in "onCreateView" as _headerHeight = getHeaderHeight(); 

Animation _hideAnimation = new Animation() { 
    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) { 
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) _headerLayout.getLayoutParams(); 
    params.topMargin = -(int) (_headerHeight * interpolatedTime); 
    _headerLayout.setLayoutParams(params); 
    } 
}; 

Animation _showAnimation = new Animation() { 
    @Override 
    protected void applyTransformation(float interpolatedTime, Transformation t) { 
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) _headerLayout.getLayoutParams(); 
    params.topMargin = (int) (_headerHeight * (interpolatedTime - 1)); 
    _headerLayout.setLayoutParams(params); 
    } 
}; 

private int getHeaderHeight() 
{ 
    _headerLayout.measure(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT); 
    return _headerLayout.getMeasuredHeight(); 
} 

скрытие заголовка:

_headerLayout.clearAnimation(); 
_headerLayout.startAnimation(_hideAnimation); 

Показаны заголовка:

_headerLayout.clearAnimation(); 
_headerLayout.startAnimation(_showAnimation); 

Вы также можете легко установить длительность анимации :

_hideAnimation.setDuration(2000) // will hide in 2 seconds 
_showAnimation.setDuration(2000) // will show in 2 seconds 
+1

Хороший ответ, хотя некоторые изъяны. (1) Перед переключением анимации необходимо очистить анимацию; (2) params.height всегда -2, поскольку используется WRAP_CONTENT. Я исправил эти два ответа. Во всяком случае, рекомендуется! – David

+0

@ Давид относительно высоты, вы правы, спасибо. Однако раньше я использовал startAnimation без clearAnimation, вы думаете, что это ошибка? –

+0

Я просто пробовал это, без ясной анимации, прямое переключение на другую анимацию не имеет никакого эффекта. Нет причин, почему, :) – David