Какой метод вызывается, когда вы проводите между фрагментами?
Вы ищете 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
Я надеюсь, что поможет вам некоторые!
Эй, это был совершенный! Спасибо за кучи за вашу помощь. Corey :) – Fishingfon
Хороший и полезный ответ. Спасибо – webo80
это выглядит интересно ... –