5

У меня есть приложение, которое я делаю, у которого есть настройка FragmentPagerAdapter с тремя фрагментами, которые можно провести между ними на главной странице.Как изменить цвет ActionBar при прокрутке между фрагментами (Material Design)?

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

Однако я не уверен, как я должен это делать. Какой метод вызывается при прокрутке фрагментов? I.E, где я должен поместить код для изменения цвета панели действий?

А также как бы получить эффект постепенного выцветания (так что он исчезает один цвет в другой)?

Я очень благодарен за помощь anyones.

Заранее спасибо

Приветствия Corey :)

ответ

13

Какой метод вызывается, когда вы проводите между фрагментами?

Вы ищете ViewPager.OnPageChangeListener.onPageScrolled. Это даст вам:

  • Поместите индекс позиции на первой странице в настоящее время отображается.
  • positionOffset Значение от [0, 1), указывающее смещение со страницы в позиции.
  • positionOffsetPixels Значение в пикселях, указывающее смещение от положения.

Хотя вам понадобятся только первые два параметра. То, что вы хотите сделать, это привязать определенный цвет к каждому из ваших фрагментов, получить как текущую страницу, так и следующую страницу, а затем объединить их вместе, используя соотношение positionOffset, чтобы создать новый фон ActionBar.

Полезный алгоритм для смешивания двух цветов на основе соотношения можно найти в новом примере Google SlidingTabStrip.0.0 вернет второй цвет, 0.5 будет возвращать даже сливаться, и 1.0 возвратит первый цвет

static int blendColors(int from, int to, float ratio) { 
    final float inverseRation = 1f - ratio; 
    final float r = Color.red(from) * ratio + Color.red(to) * inverseRation; 
    final float g = Color.green(from) * ratio + Color.green(to) * inverseRation; 
    final float b = Color.blue(from) * ratio + Color.blue(to) * inverseRation; 
    return Color.rgb((int) r, (int) g, (int) b); 
} 

Вот простой пример:

ColorFragment

public class ColorFragment extends Fragment { 

    private static final String KEY_COLOR = "colorfragment:color"; 

    /** Empty constructor as per the {@link Fragment} docs */ 
    public ColorFragment() { 
    } 

    public static ColorFragment newInstance(int color) { 
     final Bundle args = new Bundle(); 
     args.putInt(KEY_COLOR, color); 
     final ColorFragment fragment = new ColorFragment(); 
     fragment.setArguments(args); 
     return fragment; 
    } 

    @Override 
    public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { 
     final FrameLayout rootView = new FrameLayout(getActivity()); 
     rootView.setBackgroundColor(getArguments().getInt(KEY_COLOR)); 
     return rootView; 
    } 

    public int getColor() { 
     return getArguments().getInt(KEY_COLOR); 
    } 

} 

тумблера все вместе

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    // Set the ActionBar background 
    final ColorDrawable actionBarBackground = new ColorDrawable(); 
    getSupportActionBar().setBackgroundDrawable(actionBarBackground); 
    ... 
    final PagerAdapter pagerAdapter = ...; 
    ... 
    // Bind your data to your PagerAdapter 
    ... 
    final ViewPager pager = ...; 
    pager.setOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() { 

     @Override 
     public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) { 
      super.onPageScrolled(position, positionOffset, positionOffsetPixels); 
      if (position >= pagerAdapter.getCount() - 1) { 
       // Guard against ArrayIndexOutOfBoundsException 
       return; 
      } 
      // Retrieve the current and next ColorFragment 
      final ColorFragment from = (ColorFragment) pagerAdapter.getItem(position); 
      final ColorFragment to = (ColorFragment) pagerAdapter.getItem(position + 1); 
      // Blend the colors and adjust the ActionBar 
      final int blended = blendColors(to.getColor(), from.getColor(), positionOffset); 
      actionBarBackground.setColor(blended); 
     } 

    }); 
    pager.setAdapter(pagerAdapter); 
} 

Результаты

http://gfycat.com/CautiousBewitchedJabiru

Я надеюсь, что поможет вам некоторые!

+1

Эй, это был совершенный! Спасибо за кучи за вашу помощь. Corey :) – Fishingfon

+1

Хороший и полезный ответ. Спасибо – webo80

+1

это выглядит интересно ... –

1

Вы можете сделать свой FragmentPagerAdapter реализует ViewPager.OnPageChangeListener.

Затем переопределение onPageSelected

@Override 
public void onPageSelected(int position) { 
    // get the action bar here and change color 
} 

Что касается анимации изменения цвета. Я не пробовал, но это из другой StackOverflow вопрос:

Android objectAnimator animate backgroundColor of Layout