1/* This file is auto-generated from BrowseFragment.java. DO NOT MODIFY. */ 2 3/* 4 * Copyright (C) 2014 The Android Open Source Project 5 * 6 * Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except 7 * in compliance with the License. You may obtain a copy of the License at 8 * 9 * http://www.apache.org/licenses/LICENSE-2.0 10 * 11 * Unless required by applicable law or agreed to in writing, software distributed under the License 12 * is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express 13 * or implied. See the License for the specific language governing permissions and limitations under 14 * the License. 15 */ 16package android.support.v17.leanback.app; 17 18import static android.support.v7.widget.RecyclerView.NO_POSITION; 19 20import android.support.v4.app.Fragment; 21import android.support.v4.app.FragmentManager; 22import android.support.v4.app.FragmentManager.BackStackEntry; 23import android.support.v4.app.FragmentTransaction; 24import android.content.res.TypedArray; 25import android.graphics.Color; 26import android.graphics.Rect; 27import android.os.Bundle; 28import android.support.annotation.ColorInt; 29import android.support.v17.leanback.R; 30import android.support.v17.leanback.transition.TransitionHelper; 31import android.support.v17.leanback.transition.TransitionListener; 32import android.support.v17.leanback.widget.BrowseFrameLayout; 33import android.support.v17.leanback.widget.InvisibleRowPresenter; 34import android.support.v17.leanback.widget.ListRow; 35import android.support.v17.leanback.widget.ObjectAdapter; 36import android.support.v17.leanback.widget.OnItemViewClickedListener; 37import android.support.v17.leanback.widget.OnItemViewSelectedListener; 38import android.support.v17.leanback.widget.PageRow; 39import android.support.v17.leanback.widget.Presenter; 40import android.support.v17.leanback.widget.PresenterSelector; 41import android.support.v17.leanback.widget.Row; 42import android.support.v17.leanback.widget.RowHeaderPresenter; 43import android.support.v17.leanback.widget.RowPresenter; 44import android.support.v17.leanback.widget.ScaleFrameLayout; 45import android.support.v17.leanback.widget.TitleViewAdapter; 46import android.support.v17.leanback.widget.VerticalGridView; 47import android.support.v4.view.ViewCompat; 48import android.support.v7.widget.RecyclerView; 49import android.util.Log; 50import android.view.LayoutInflater; 51import android.view.View; 52import android.view.ViewGroup; 53import android.view.ViewGroup.MarginLayoutParams; 54import android.view.ViewTreeObserver; 55 56import java.util.HashMap; 57import java.util.Map; 58 59/** 60 * A fragment for creating Leanback browse screens. It is composed of a 61 * RowsSupportFragment and a HeadersSupportFragment. 62 * <p> 63 * A BrowseSupportFragment renders the elements of its {@link ObjectAdapter} as a set 64 * of rows in a vertical list. The elements in this adapter must be subclasses 65 * of {@link Row}. 66 * <p> 67 * The HeadersSupportFragment can be set to be either shown or hidden by default, or 68 * may be disabled entirely. See {@link #setHeadersState} for details. 69 * <p> 70 * By default the BrowseSupportFragment includes support for returning to the headers 71 * when the user presses Back. For Activities that customize {@link 72 * android.support.v4.app.FragmentActivity#onBackPressed()}, you must disable this default Back key support by 73 * calling {@link #setHeadersTransitionOnBackEnabled(boolean)} with false and 74 * use {@link BrowseSupportFragment.BrowseTransitionListener} and 75 * {@link #startHeadersTransition(boolean)}. 76 * <p> 77 * The recommended theme to use with a BrowseSupportFragment is 78 * {@link android.support.v17.leanback.R.style#Theme_Leanback_Browse}. 79 * </p> 80 */ 81public class BrowseSupportFragment extends BaseSupportFragment { 82 83 // BUNDLE attribute for saving header show/hide status when backstack is used: 84 static final String HEADER_STACK_INDEX = "headerStackIndex"; 85 // BUNDLE attribute for saving header show/hide status when backstack is not used: 86 static final String HEADER_SHOW = "headerShow"; 87 private static final String IS_PAGE_ROW = "isPageRow"; 88 private static final String CURRENT_SELECTED_POSITION = "currentSelectedPosition"; 89 90 final class BackStackListener implements FragmentManager.OnBackStackChangedListener { 91 int mLastEntryCount; 92 int mIndexOfHeadersBackStack; 93 94 BackStackListener() { 95 mLastEntryCount = getFragmentManager().getBackStackEntryCount(); 96 mIndexOfHeadersBackStack = -1; 97 } 98 99 void load(Bundle savedInstanceState) { 100 if (savedInstanceState != null) { 101 mIndexOfHeadersBackStack = savedInstanceState.getInt(HEADER_STACK_INDEX, -1); 102 mShowingHeaders = mIndexOfHeadersBackStack == -1; 103 } else { 104 if (!mShowingHeaders) { 105 getFragmentManager().beginTransaction() 106 .addToBackStack(mWithHeadersBackStackName).commit(); 107 } 108 } 109 } 110 111 void save(Bundle outState) { 112 outState.putInt(HEADER_STACK_INDEX, mIndexOfHeadersBackStack); 113 } 114 115 116 @Override 117 public void onBackStackChanged() { 118 if (getFragmentManager() == null) { 119 Log.w(TAG, "getFragmentManager() is null, stack:", new Exception()); 120 return; 121 } 122 int count = getFragmentManager().getBackStackEntryCount(); 123 // if backstack is growing and last pushed entry is "headers" backstack, 124 // remember the index of the entry. 125 if (count > mLastEntryCount) { 126 BackStackEntry entry = getFragmentManager().getBackStackEntryAt(count - 1); 127 if (mWithHeadersBackStackName.equals(entry.getName())) { 128 mIndexOfHeadersBackStack = count - 1; 129 } 130 } else if (count < mLastEntryCount) { 131 // if popped "headers" backstack, initiate the show header transition if needed 132 if (mIndexOfHeadersBackStack >= count) { 133 if (!isHeadersDataReady()) { 134 // if main fragment was restored first before BrowseSupportFragment's adapater gets 135 // restored: dont start header transition, but add the entry back. 136 getFragmentManager().beginTransaction() 137 .addToBackStack(mWithHeadersBackStackName).commit(); 138 return; 139 } 140 mIndexOfHeadersBackStack = -1; 141 if (!mShowingHeaders) { 142 startHeadersTransitionInternal(true); 143 } 144 } 145 } 146 mLastEntryCount = count; 147 } 148 } 149 150 /** 151 * Listener for transitions between browse headers and rows. 152 */ 153 public static class BrowseTransitionListener { 154 /** 155 * Callback when headers transition starts. 156 * 157 * @param withHeaders True if the transition will result in headers 158 * being shown, false otherwise. 159 */ 160 public void onHeadersTransitionStart(boolean withHeaders) { 161 } 162 /** 163 * Callback when headers transition stops. 164 * 165 * @param withHeaders True if the transition will result in headers 166 * being shown, false otherwise. 167 */ 168 public void onHeadersTransitionStop(boolean withHeaders) { 169 } 170 } 171 172 private class SetSelectionRunnable implements Runnable { 173 static final int TYPE_INVALID = -1; 174 static final int TYPE_INTERNAL_SYNC = 0; 175 static final int TYPE_USER_REQUEST = 1; 176 177 private int mPosition; 178 private int mType; 179 private boolean mSmooth; 180 181 SetSelectionRunnable() { 182 reset(); 183 } 184 185 void post(int position, int type, boolean smooth) { 186 // Posting the set selection, rather than calling it immediately, prevents an issue 187 // with adapter changes. Example: a row is added before the current selected row; 188 // first the fast lane view updates its selection, then the rows fragment has that 189 // new selection propagated immediately; THEN the rows view processes the same adapter 190 // change and moves the selection again. 191 if (type >= mType) { 192 mPosition = position; 193 mType = type; 194 mSmooth = smooth; 195 mBrowseFrame.removeCallbacks(this); 196 mBrowseFrame.post(this); 197 } 198 } 199 200 @Override 201 public void run() { 202 setSelection(mPosition, mSmooth); 203 reset(); 204 } 205 206 private void reset() { 207 mPosition = -1; 208 mType = TYPE_INVALID; 209 mSmooth = false; 210 } 211 } 212 213 /** 214 * Possible set of actions that {@link BrowseSupportFragment} exposes to clients. Custom 215 * fragments can interact with {@link BrowseSupportFragment} using this interface. 216 */ 217 public interface FragmentHost { 218 /** 219 * Fragments are required to invoke this callback once their view is created 220 * inside {@link Fragment#onViewCreated} method. {@link BrowseSupportFragment} starts the entrance 221 * animation only after receiving this callback. Failure to invoke this method 222 * will lead to fragment not showing up. 223 * 224 * @param fragmentAdapter {@link MainFragmentAdapter} used by the current fragment. 225 */ 226 void notifyViewCreated(MainFragmentAdapter fragmentAdapter); 227 228 /** 229 * Fragments mapped to {@link PageRow} are required to invoke this callback once their data 230 * is created for transition, the entrance animation only after receiving this callback. 231 * Failure to invoke this method will lead to fragment not showing up. 232 * 233 * @param fragmentAdapter {@link MainFragmentAdapter} used by the current fragment. 234 */ 235 void notifyDataReady(MainFragmentAdapter fragmentAdapter); 236 237 /** 238 * Show or hide title view in {@link BrowseSupportFragment} for fragments mapped to 239 * {@link PageRow}. Otherwise the request is ignored, in that case BrowseSupportFragment is fully 240 * in control of showing/hiding title view. 241 * <p> 242 * When HeadersSupportFragment is visible, BrowseSupportFragment will hide search affordance view if 243 * there are other focusable rows above currently focused row. 244 * 245 * @param show Boolean indicating whether or not to show the title view. 246 */ 247 void showTitleView(boolean show); 248 } 249 250 /** 251 * Default implementation of {@link FragmentHost} that is used only by 252 * {@link BrowseSupportFragment}. 253 */ 254 private final class FragmentHostImpl implements FragmentHost { 255 boolean mShowTitleView = true; 256 boolean mDataReady = false; 257 258 @Override 259 public void notifyViewCreated(MainFragmentAdapter fragmentAdapter) { 260 performPendingStates(); 261 } 262 263 @Override 264 public void notifyDataReady(MainFragmentAdapter fragmentAdapter) { 265 mDataReady = true; 266 267 // If fragment host is not the currently active fragment (in BrowseSupportFragment), then 268 // ignore the request. 269 if (mMainFragmentAdapter == null || mMainFragmentAdapter.getFragmentHost() != this) { 270 return; 271 } 272 273 // We only honor showTitle request for PageRows. 274 if (!mIsPageRow) { 275 return; 276 } 277 278 performPendingStates(); 279 } 280 281 @Override 282 public void showTitleView(boolean show) { 283 mShowTitleView = show; 284 285 // If fragment host is not the currently active fragment (in BrowseSupportFragment), then 286 // ignore the request. 287 if (mMainFragmentAdapter == null || mMainFragmentAdapter.getFragmentHost() != this) { 288 return; 289 } 290 291 // We only honor showTitle request for PageRows. 292 if (!mIsPageRow) { 293 return; 294 } 295 296 updateTitleViewVisibility(); 297 } 298 } 299 300 /** 301 * Interface that defines the interaction between {@link BrowseSupportFragment} and it's main 302 * content fragment. The key method is {@link MainFragmentAdapter#getFragment()}, 303 * it will be used to get the fragment to be shown in the content section. Clients can 304 * provide any implementation of fragment and customize it's interaction with 305 * {@link BrowseSupportFragment} by overriding the necessary methods. 306 * 307 * <p> 308 * Clients are expected to provide 309 * an instance of {@link MainFragmentAdapterRegistry} which will be responsible for providing 310 * implementations of {@link MainFragmentAdapter} for given content types. Currently 311 * we support different types of content - {@link ListRow}, {@link PageRow} or any subtype 312 * of {@link Row}. We provide an out of the box adapter implementation for any rows other than 313 * {@link PageRow} - {@link android.support.v17.leanback.app.RowsSupportFragment.MainFragmentAdapter}. 314 * 315 * <p> 316 * {@link PageRow} is intended to give full flexibility to developers in terms of Fragment 317 * design. Users will have to provide an implementation of {@link MainFragmentAdapter} 318 * and provide that through {@link MainFragmentAdapterRegistry}. 319 * {@link MainFragmentAdapter} implementation can supply any fragment and override 320 * just those interactions that makes sense. 321 */ 322 public static class MainFragmentAdapter<T extends Fragment> { 323 private boolean mScalingEnabled; 324 private final T mFragment; 325 private FragmentHostImpl mFragmentHost; 326 327 public MainFragmentAdapter(T fragment) { 328 this.mFragment = fragment; 329 } 330 331 public final T getFragment() { 332 return mFragment; 333 } 334 335 /** 336 * Returns whether its scrolling. 337 */ 338 public boolean isScrolling() { 339 return false; 340 } 341 342 /** 343 * Set the visibility of titles/hovercard of browse rows. 344 */ 345 public void setExpand(boolean expand) { 346 } 347 348 /** 349 * For rows that willing to participate entrance transition, this function 350 * hide views if afterTransition is true, show views if afterTransition is false. 351 */ 352 public void setEntranceTransitionState(boolean state) { 353 } 354 355 /** 356 * Sets the window alignment and also the pivots for scale operation. 357 */ 358 public void setAlignment(int windowAlignOffsetFromTop) { 359 } 360 361 /** 362 * Callback indicating transition prepare start. 363 */ 364 public boolean onTransitionPrepare() { 365 return false; 366 } 367 368 /** 369 * Callback indicating transition start. 370 */ 371 public void onTransitionStart() { 372 } 373 374 /** 375 * Callback indicating transition end. 376 */ 377 public void onTransitionEnd() { 378 } 379 380 /** 381 * Returns whether row scaling is enabled. 382 */ 383 public boolean isScalingEnabled() { 384 return mScalingEnabled; 385 } 386 387 /** 388 * Sets the row scaling property. 389 */ 390 public void setScalingEnabled(boolean scalingEnabled) { 391 this.mScalingEnabled = scalingEnabled; 392 } 393 394 /** 395 * Returns the current host interface so that main fragment can interact with 396 * {@link BrowseSupportFragment}. 397 */ 398 public final FragmentHost getFragmentHost() { 399 return mFragmentHost; 400 } 401 402 void setFragmentHost(FragmentHostImpl fragmentHost) { 403 this.mFragmentHost = fragmentHost; 404 } 405 } 406 407 /** 408 * Interface to be implemented by all fragments for providing an instance of 409 * {@link MainFragmentAdapter}. Both {@link RowsSupportFragment} and custom fragment provided 410 * against {@link PageRow} will need to implement this interface. 411 */ 412 public interface MainFragmentAdapterProvider { 413 /** 414 * Returns an instance of {@link MainFragmentAdapter} that {@link BrowseSupportFragment} 415 * would use to communicate with the target fragment. 416 */ 417 MainFragmentAdapter getMainFragmentAdapter(); 418 } 419 420 /** 421 * Interface to be implemented by {@link RowsSupportFragment} and it's subclasses for providing 422 * an instance of {@link MainFragmentRowsAdapter}. 423 */ 424 public interface MainFragmentRowsAdapterProvider { 425 /** 426 * Returns an instance of {@link MainFragmentRowsAdapter} that {@link BrowseSupportFragment} 427 * would use to communicate with the target fragment. 428 */ 429 MainFragmentRowsAdapter getMainFragmentRowsAdapter(); 430 } 431 432 /** 433 * This is used to pass information to {@link RowsSupportFragment} or its subclasses. 434 * {@link BrowseSupportFragment} uses this interface to pass row based interaction events to 435 * the target fragment. 436 */ 437 public static class MainFragmentRowsAdapter<T extends Fragment> { 438 private final T mFragment; 439 440 public MainFragmentRowsAdapter(T fragment) { 441 if (fragment == null) { 442 throw new IllegalArgumentException("Fragment can't be null"); 443 } 444 this.mFragment = fragment; 445 } 446 447 public final T getFragment() { 448 return mFragment; 449 } 450 /** 451 * Set the visibility titles/hover of browse rows. 452 */ 453 public void setAdapter(ObjectAdapter adapter) { 454 } 455 456 /** 457 * Sets an item clicked listener on the fragment. 458 */ 459 public void setOnItemViewClickedListener(OnItemViewClickedListener listener) { 460 } 461 462 /** 463 * Sets an item selection listener. 464 */ 465 public void setOnItemViewSelectedListener(OnItemViewSelectedListener listener) { 466 } 467 468 /** 469 * Selects a Row and perform an optional task on the Row. 470 */ 471 public void setSelectedPosition(int rowPosition, 472 boolean smooth, 473 final Presenter.ViewHolderTask rowHolderTask) { 474 } 475 476 /** 477 * Selects a Row. 478 */ 479 public void setSelectedPosition(int rowPosition, boolean smooth) { 480 } 481 482 /** 483 * Returns the selected position. 484 */ 485 public int getSelectedPosition() { 486 return 0; 487 } 488 } 489 490 private boolean createMainFragment(ObjectAdapter adapter, int position) { 491 Object item = null; 492 if (adapter == null || adapter.size() == 0) { 493 return false; 494 } else { 495 if (position < 0) { 496 position = 0; 497 } else if (position >= adapter.size()) { 498 throw new IllegalArgumentException( 499 String.format("Invalid position %d requested", position)); 500 } 501 item = adapter.get(position); 502 } 503 504 mSelectedPosition = position; 505 boolean oldIsPageRow = mIsPageRow; 506 mIsPageRow = item instanceof PageRow; 507 boolean swap; 508 509 if (mMainFragment == null) { 510 swap = true; 511 } else { 512 if (oldIsPageRow) { 513 swap = true; 514 } else { 515 swap = mIsPageRow; 516 } 517 } 518 519 if (swap) { 520 mMainFragment = mMainFragmentAdapterRegistry.createFragment(item); 521 if (!(mMainFragment instanceof MainFragmentAdapterProvider)) { 522 throw new IllegalArgumentException( 523 "Fragment must implement MainFragmentAdapterProvider"); 524 } 525 526 mMainFragmentAdapter = ((MainFragmentAdapterProvider)mMainFragment) 527 .getMainFragmentAdapter(); 528 mMainFragmentAdapter.setFragmentHost(new FragmentHostImpl()); 529 if (!mIsPageRow) { 530 if (mMainFragment instanceof MainFragmentRowsAdapterProvider) { 531 mMainFragmentRowsAdapter = ((MainFragmentRowsAdapterProvider)mMainFragment) 532 .getMainFragmentRowsAdapter(); 533 } else { 534 mMainFragmentRowsAdapter = null; 535 } 536 mIsPageRow = mMainFragmentRowsAdapter == null; 537 } else { 538 mMainFragmentRowsAdapter = null; 539 } 540 } 541 542 return swap; 543 } 544 545 /** 546 * Factory class responsible for creating fragment given the current item. {@link ListRow} 547 * should returns {@link RowsSupportFragment} or it's subclass whereas {@link PageRow} 548 * can return any fragment class. 549 */ 550 public abstract static class FragmentFactory<T extends Fragment> { 551 public abstract T createFragment(Object row); 552 } 553 554 /** 555 * FragmentFactory implementation for {@link ListRow}. 556 */ 557 public static class ListRowFragmentFactory extends FragmentFactory<RowsSupportFragment> { 558 @Override 559 public RowsSupportFragment createFragment(Object row) { 560 return new RowsSupportFragment(); 561 } 562 } 563 564 /** 565 * Registry class maintaining the mapping of {@link Row} subclasses to {@link FragmentFactory}. 566 * BrowseRowFragment automatically registers {@link ListRowFragmentFactory} for 567 * handling {@link ListRow}. Developers can override that and also if they want to 568 * use custom fragment, they can register a custom {@link FragmentFactory} 569 * against {@link PageRow}. 570 */ 571 public final static class MainFragmentAdapterRegistry { 572 private final Map<Class, FragmentFactory> mItemToFragmentFactoryMapping = new HashMap(); 573 private final static FragmentFactory sDefaultFragmentFactory = new ListRowFragmentFactory(); 574 575 public MainFragmentAdapterRegistry() { 576 registerFragment(ListRow.class, sDefaultFragmentFactory); 577 } 578 579 public void registerFragment(Class rowClass, FragmentFactory factory) { 580 mItemToFragmentFactoryMapping.put(rowClass, factory); 581 } 582 583 public Fragment createFragment(Object item) { 584 if (item == null) { 585 throw new IllegalArgumentException("Item can't be null"); 586 } 587 588 FragmentFactory fragmentFactory = mItemToFragmentFactoryMapping.get(item.getClass()); 589 if (fragmentFactory == null && !(item instanceof PageRow)) { 590 fragmentFactory = sDefaultFragmentFactory; 591 } 592 593 return fragmentFactory.createFragment(item); 594 } 595 } 596 597 private static final String TAG = "BrowseSupportFragment"; 598 599 private static final String LB_HEADERS_BACKSTACK = "lbHeadersBackStack_"; 600 601 private static boolean DEBUG = false; 602 603 /** The headers fragment is enabled and shown by default. */ 604 public static final int HEADERS_ENABLED = 1; 605 606 /** The headers fragment is enabled and hidden by default. */ 607 public static final int HEADERS_HIDDEN = 2; 608 609 /** The headers fragment is disabled and will never be shown. */ 610 public static final int HEADERS_DISABLED = 3; 611 612 private MainFragmentAdapterRegistry mMainFragmentAdapterRegistry 613 = new MainFragmentAdapterRegistry(); 614 private MainFragmentAdapter mMainFragmentAdapter; 615 private Fragment mMainFragment; 616 private HeadersSupportFragment mHeadersSupportFragment; 617 private MainFragmentRowsAdapter mMainFragmentRowsAdapter; 618 619 private ObjectAdapter mAdapter; 620 private PresenterSelector mAdapterPresenter; 621 private PresenterSelector mWrappingPresenterSelector; 622 623 private int mHeadersState = HEADERS_ENABLED; 624 private int mBrandColor = Color.TRANSPARENT; 625 private boolean mBrandColorSet; 626 627 private BrowseFrameLayout mBrowseFrame; 628 private ScaleFrameLayout mScaleFrameLayout; 629 private boolean mHeadersBackStackEnabled = true; 630 private String mWithHeadersBackStackName; 631 private boolean mShowingHeaders = true; 632 private boolean mCanShowHeaders = true; 633 private int mContainerListMarginStart; 634 private int mContainerListAlignTop; 635 private boolean mMainFragmentScaleEnabled = true; 636 private OnItemViewSelectedListener mExternalOnItemViewSelectedListener; 637 private OnItemViewClickedListener mOnItemViewClickedListener; 638 private int mSelectedPosition = -1; 639 private float mScaleFactor; 640 private boolean mIsPageRow; 641 642 private PresenterSelector mHeaderPresenterSelector; 643 private final SetSelectionRunnable mSetSelectionRunnable = new SetSelectionRunnable(); 644 645 // transition related: 646 private Object mSceneWithHeaders; 647 private Object mSceneWithoutHeaders; 648 private Object mSceneAfterEntranceTransition; 649 private Object mHeadersTransition; 650 private BackStackListener mBackStackChangedListener; 651 private BrowseTransitionListener mBrowseTransitionListener; 652 653 private static final String ARG_TITLE = BrowseSupportFragment.class.getCanonicalName() + ".title"; 654 private static final String ARG_HEADERS_STATE = 655 BrowseSupportFragment.class.getCanonicalName() + ".headersState"; 656 657 /** 658 * Creates arguments for a browse fragment. 659 * 660 * @param args The Bundle to place arguments into, or null if the method 661 * should return a new Bundle. 662 * @param title The title of the BrowseSupportFragment. 663 * @param headersState The initial state of the headers of the 664 * BrowseSupportFragment. Must be one of {@link #HEADERS_ENABLED}, {@link 665 * #HEADERS_HIDDEN}, or {@link #HEADERS_DISABLED}. 666 * @return A Bundle with the given arguments for creating a BrowseSupportFragment. 667 */ 668 public static Bundle createArgs(Bundle args, String title, int headersState) { 669 if (args == null) { 670 args = new Bundle(); 671 } 672 args.putString(ARG_TITLE, title); 673 args.putInt(ARG_HEADERS_STATE, headersState); 674 return args; 675 } 676 677 /** 678 * Sets the brand color for the browse fragment. The brand color is used as 679 * the primary color for UI elements in the browse fragment. For example, 680 * the background color of the headers fragment uses the brand color. 681 * 682 * @param color The color to use as the brand color of the fragment. 683 */ 684 public void setBrandColor(@ColorInt int color) { 685 mBrandColor = color; 686 mBrandColorSet = true; 687 688 if (mHeadersSupportFragment != null) { 689 mHeadersSupportFragment.setBackgroundColor(mBrandColor); 690 } 691 } 692 693 /** 694 * Returns the brand color for the browse fragment. 695 * The default is transparent. 696 */ 697 @ColorInt 698 public int getBrandColor() { 699 return mBrandColor; 700 } 701 702 /** 703 * Wrapping app provided PresenterSelector to support InvisibleRowPresenter for SectionRow 704 * DividerRow and PageRow. 705 */ 706 private void createAndSetWrapperPresenter() { 707 final PresenterSelector adapterPresenter = mAdapter.getPresenterSelector(); 708 if (adapterPresenter == null) { 709 throw new IllegalArgumentException("Adapter.getPresenterSelector() is null"); 710 } 711 if (adapterPresenter == mAdapterPresenter) { 712 return; 713 } 714 mAdapterPresenter = adapterPresenter; 715 716 Presenter[] presenters = adapterPresenter.getPresenters(); 717 final Presenter invisibleRowPresenter = new InvisibleRowPresenter(); 718 final Presenter[] allPresenters = new Presenter[presenters.length + 1]; 719 System.arraycopy(allPresenters, 0, presenters, 0, presenters.length); 720 allPresenters[allPresenters.length - 1] = invisibleRowPresenter; 721 mAdapter.setPresenterSelector(new PresenterSelector() { 722 @Override 723 public Presenter getPresenter(Object item) { 724 Row row = (Row) item; 725 if (row.isRenderedAsRowView()) { 726 return adapterPresenter.getPresenter(item); 727 } else { 728 return invisibleRowPresenter; 729 } 730 } 731 732 @Override 733 public Presenter[] getPresenters() { 734 return allPresenters; 735 } 736 }); 737 } 738 739 /** 740 * Sets the adapter containing the rows for the fragment. 741 * 742 * <p>The items referenced by the adapter must be be derived from 743 * {@link Row}. These rows will be used by the rows fragment and the headers 744 * fragment (if not disabled) to render the browse rows. 745 * 746 * @param adapter An ObjectAdapter for the browse rows. All items must 747 * derive from {@link Row}. 748 */ 749 public void setAdapter(ObjectAdapter adapter) { 750 mAdapter = adapter; 751 createAndSetWrapperPresenter(); 752 if (getView() == null) { 753 return; 754 } 755 replaceMainFragment(mSelectedPosition); 756 757 if (adapter != null) { 758 if (mMainFragmentRowsAdapter != null) { 759 mMainFragmentRowsAdapter.setAdapter(adapter); 760 } 761 mHeadersSupportFragment.setAdapter(adapter); 762 } 763 } 764 765 public final MainFragmentAdapterRegistry getMainFragmentRegistry() { 766 return mMainFragmentAdapterRegistry; 767 } 768 769 /** 770 * Returns the adapter containing the rows for the fragment. 771 */ 772 public ObjectAdapter getAdapter() { 773 return mAdapter; 774 } 775 776 /** 777 * Sets an item selection listener. 778 */ 779 public void setOnItemViewSelectedListener(OnItemViewSelectedListener listener) { 780 mExternalOnItemViewSelectedListener = listener; 781 } 782 783 /** 784 * Returns an item selection listener. 785 */ 786 public OnItemViewSelectedListener getOnItemViewSelectedListener() { 787 return mExternalOnItemViewSelectedListener; 788 } 789 790 /** 791 * Get RowsSupportFragment if it's bound to BrowseSupportFragment or null if either BrowseSupportFragment has 792 * not been created yet or a different fragment is bound to it. 793 * 794 * @return RowsSupportFragment if it's bound to BrowseSupportFragment or null otherwise. 795 */ 796 public RowsSupportFragment getRowsSupportFragment() { 797 if (mMainFragment instanceof RowsSupportFragment) { 798 return (RowsSupportFragment) mMainFragment; 799 } 800 801 return null; 802 } 803 804 /** 805 * Get currently bound HeadersSupportFragment or null if HeadersSupportFragment has not been created yet. 806 * @return Currently bound HeadersSupportFragment or null if HeadersSupportFragment has not been created yet. 807 */ 808 public HeadersSupportFragment getHeadersSupportFragment() { 809 return mHeadersSupportFragment; 810 } 811 812 /** 813 * Sets an item clicked listener on the fragment. 814 * OnItemViewClickedListener will override {@link View.OnClickListener} that 815 * item presenter sets during {@link Presenter#onCreateViewHolder(ViewGroup)}. 816 * So in general, developer should choose one of the listeners but not both. 817 */ 818 public void setOnItemViewClickedListener(OnItemViewClickedListener listener) { 819 mOnItemViewClickedListener = listener; 820 if (mMainFragmentRowsAdapter != null) { 821 mMainFragmentRowsAdapter.setOnItemViewClickedListener(listener); 822 } 823 } 824 825 /** 826 * Returns the item Clicked listener. 827 */ 828 public OnItemViewClickedListener getOnItemViewClickedListener() { 829 return mOnItemViewClickedListener; 830 } 831 832 /** 833 * Starts a headers transition. 834 * 835 * <p>This method will begin a transition to either show or hide the 836 * headers, depending on the value of withHeaders. If headers are disabled 837 * for this browse fragment, this method will throw an exception. 838 * 839 * @param withHeaders True if the headers should transition to being shown, 840 * false if the transition should result in headers being hidden. 841 */ 842 public void startHeadersTransition(boolean withHeaders) { 843 if (!mCanShowHeaders) { 844 throw new IllegalStateException("Cannot start headers transition"); 845 } 846 if (isInHeadersTransition() || mShowingHeaders == withHeaders) { 847 return; 848 } 849 startHeadersTransitionInternal(withHeaders); 850 } 851 852 /** 853 * Returns true if the headers transition is currently running. 854 */ 855 public boolean isInHeadersTransition() { 856 return mHeadersTransition != null; 857 } 858 859 /** 860 * Returns true if headers are shown. 861 */ 862 public boolean isShowingHeaders() { 863 return mShowingHeaders; 864 } 865 866 /** 867 * Sets a listener for browse fragment transitions. 868 * 869 * @param listener The listener to call when a browse headers transition 870 * begins or ends. 871 */ 872 public void setBrowseTransitionListener(BrowseTransitionListener listener) { 873 mBrowseTransitionListener = listener; 874 } 875 876 /** 877 * @deprecated use {@link BrowseSupportFragment#enableMainFragmentScaling(boolean)} instead. 878 * 879 * @param enable true to enable row scaling 880 */ 881 @Deprecated 882 public void enableRowScaling(boolean enable) { 883 enableMainFragmentScaling(enable); 884 } 885 886 /** 887 * Enables scaling of main fragment when headers are present. For the page/row fragment, 888 * scaling is enabled only when both this method and 889 * {@link MainFragmentAdapter#isScalingEnabled()} are enabled. 890 * 891 * @param enable true to enable row scaling 892 */ 893 public void enableMainFragmentScaling(boolean enable) { 894 mMainFragmentScaleEnabled = enable; 895 } 896 897 private void startHeadersTransitionInternal(final boolean withHeaders) { 898 if (getFragmentManager().isDestroyed()) { 899 return; 900 } 901 if (!isHeadersDataReady()) { 902 return; 903 } 904 mShowingHeaders = withHeaders; 905 mMainFragmentAdapter.onTransitionPrepare(); 906 mMainFragmentAdapter.onTransitionStart(); 907 onExpandTransitionStart(!withHeaders, new Runnable() { 908 @Override 909 public void run() { 910 mHeadersSupportFragment.onTransitionPrepare(); 911 mHeadersSupportFragment.onTransitionStart(); 912 createHeadersTransition(); 913 if (mBrowseTransitionListener != null) { 914 mBrowseTransitionListener.onHeadersTransitionStart(withHeaders); 915 } 916 TransitionHelper.runTransition( 917 withHeaders ? mSceneWithHeaders : mSceneWithoutHeaders, mHeadersTransition); 918 if (mHeadersBackStackEnabled) { 919 if (!withHeaders) { 920 getFragmentManager().beginTransaction() 921 .addToBackStack(mWithHeadersBackStackName).commit(); 922 } else { 923 int index = mBackStackChangedListener.mIndexOfHeadersBackStack; 924 if (index >= 0) { 925 BackStackEntry entry = getFragmentManager().getBackStackEntryAt(index); 926 getFragmentManager().popBackStackImmediate(entry.getId(), 927 FragmentManager.POP_BACK_STACK_INCLUSIVE); 928 } 929 } 930 } 931 } 932 }); 933 } 934 935 boolean isVerticalScrolling() { 936 // don't run transition 937 return mHeadersSupportFragment.isScrolling() || mMainFragmentAdapter.isScrolling(); 938 } 939 940 941 private final BrowseFrameLayout.OnFocusSearchListener mOnFocusSearchListener = 942 new BrowseFrameLayout.OnFocusSearchListener() { 943 @Override 944 public View onFocusSearch(View focused, int direction) { 945 // if headers is running transition, focus stays 946 if (mCanShowHeaders && isInHeadersTransition()) { 947 return focused; 948 } 949 if (DEBUG) Log.v(TAG, "onFocusSearch focused " + focused + " + direction " + direction); 950 951 if (getTitleView() != null && focused != getTitleView() && 952 direction == View.FOCUS_UP) { 953 return getTitleView(); 954 } 955 if (getTitleView() != null && getTitleView().hasFocus() && 956 direction == View.FOCUS_DOWN) { 957 return mCanShowHeaders && mShowingHeaders ? 958 mHeadersSupportFragment.getVerticalGridView() : mMainFragment.getView(); 959 } 960 961 boolean isRtl = ViewCompat.getLayoutDirection(focused) == View.LAYOUT_DIRECTION_RTL; 962 int towardStart = isRtl ? View.FOCUS_RIGHT : View.FOCUS_LEFT; 963 int towardEnd = isRtl ? View.FOCUS_LEFT : View.FOCUS_RIGHT; 964 if (mCanShowHeaders && direction == towardStart) { 965 if (isVerticalScrolling() || mShowingHeaders || !isHeadersDataReady()) { 966 return focused; 967 } 968 return mHeadersSupportFragment.getVerticalGridView(); 969 } else if (direction == towardEnd) { 970 if (isVerticalScrolling()) { 971 return focused; 972 } 973 return mMainFragment.getView(); 974 } else if (direction == View.FOCUS_DOWN && mShowingHeaders) { 975 // disable focus_down moving into PageFragment. 976 return focused; 977 } else { 978 return null; 979 } 980 } 981 }; 982 983 private final boolean isHeadersDataReady() { 984 return mAdapter != null && mAdapter.size() != 0; 985 } 986 987 private final BrowseFrameLayout.OnChildFocusListener mOnChildFocusListener = 988 new BrowseFrameLayout.OnChildFocusListener() { 989 990 @Override 991 public boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) { 992 if (getChildFragmentManager().isDestroyed()) { 993 return true; 994 } 995 // Make sure not changing focus when requestFocus() is called. 996 if (mCanShowHeaders && mShowingHeaders) { 997 if (mHeadersSupportFragment != null && mHeadersSupportFragment.getView() != null && 998 mHeadersSupportFragment.getView().requestFocus(direction, previouslyFocusedRect)) { 999 return true; 1000 } 1001 } 1002 if (mMainFragment != null && mMainFragment.getView() != null && 1003 mMainFragment.getView().requestFocus(direction, previouslyFocusedRect)) { 1004 return true; 1005 } 1006 if (getTitleView() != null && 1007 getTitleView().requestFocus(direction, previouslyFocusedRect)) { 1008 return true; 1009 } 1010 return false; 1011 } 1012 1013 @Override 1014 public void onRequestChildFocus(View child, View focused) { 1015 if (getChildFragmentManager().isDestroyed()) { 1016 return; 1017 } 1018 if (!mCanShowHeaders || isInHeadersTransition()) return; 1019 int childId = child.getId(); 1020 if (childId == R.id.browse_container_dock && mShowingHeaders) { 1021 startHeadersTransitionInternal(false); 1022 } else if (childId == R.id.browse_headers_dock && !mShowingHeaders) { 1023 startHeadersTransitionInternal(true); 1024 } 1025 } 1026 }; 1027 1028 @Override 1029 public void onSaveInstanceState(Bundle outState) { 1030 super.onSaveInstanceState(outState); 1031 outState.putInt(CURRENT_SELECTED_POSITION, mSelectedPosition); 1032 outState.putBoolean(IS_PAGE_ROW, mIsPageRow); 1033 1034 if (mBackStackChangedListener != null) { 1035 mBackStackChangedListener.save(outState); 1036 } else { 1037 outState.putBoolean(HEADER_SHOW, mShowingHeaders); 1038 } 1039 } 1040 1041 @Override 1042 public void onCreate(Bundle savedInstanceState) { 1043 super.onCreate(savedInstanceState); 1044 TypedArray ta = getActivity().obtainStyledAttributes(R.styleable.LeanbackTheme); 1045 mContainerListMarginStart = (int) ta.getDimension( 1046 R.styleable.LeanbackTheme_browseRowsMarginStart, getActivity().getResources() 1047 .getDimensionPixelSize(R.dimen.lb_browse_rows_margin_start)); 1048 mContainerListAlignTop = (int) ta.getDimension( 1049 R.styleable.LeanbackTheme_browseRowsMarginTop, getActivity().getResources() 1050 .getDimensionPixelSize(R.dimen.lb_browse_rows_margin_top)); 1051 ta.recycle(); 1052 1053 readArguments(getArguments()); 1054 1055 if (mCanShowHeaders) { 1056 if (mHeadersBackStackEnabled) { 1057 mWithHeadersBackStackName = LB_HEADERS_BACKSTACK + this; 1058 mBackStackChangedListener = new BackStackListener(); 1059 getFragmentManager().addOnBackStackChangedListener(mBackStackChangedListener); 1060 mBackStackChangedListener.load(savedInstanceState); 1061 } else { 1062 if (savedInstanceState != null) { 1063 mShowingHeaders = savedInstanceState.getBoolean(HEADER_SHOW); 1064 } 1065 } 1066 } 1067 1068 mScaleFactor = getResources().getFraction(R.fraction.lb_browse_rows_scale, 1, 1); 1069 } 1070 1071 @Override 1072 public void onDestroyView() { 1073 mMainFragmentRowsAdapter = null; 1074 mMainFragmentAdapter = null; 1075 mMainFragment = null; 1076 mHeadersSupportFragment = null; 1077 super.onDestroyView(); 1078 } 1079 1080 @Override 1081 public void onDestroy() { 1082 if (mBackStackChangedListener != null) { 1083 getFragmentManager().removeOnBackStackChangedListener(mBackStackChangedListener); 1084 } 1085 super.onDestroy(); 1086 } 1087 1088 @Override 1089 public View onCreateView(LayoutInflater inflater, ViewGroup container, 1090 Bundle savedInstanceState) { 1091 1092 if (getChildFragmentManager().findFragmentById(R.id.scale_frame) == null) { 1093 mHeadersSupportFragment = new HeadersSupportFragment(); 1094 1095 createMainFragment(mAdapter, mSelectedPosition); 1096 FragmentTransaction ft = getChildFragmentManager().beginTransaction() 1097 .replace(R.id.browse_headers_dock, mHeadersSupportFragment); 1098 1099 if (mMainFragment != null) { 1100 ft.replace(R.id.scale_frame, mMainFragment); 1101 } else { 1102 // Empty adapter used to guard against lazy adapter loading. When this 1103 // fragment is instantiated, mAdapter might not have the data or might not 1104 // have been set. In either of those cases mFragmentAdapter will be null. 1105 // This way we can maintain the invariant that mMainFragmentAdapter is never 1106 // null and it avoids doing null checks all over the code. 1107 mMainFragmentAdapter = new MainFragmentAdapter(null); 1108 mMainFragmentAdapter.setFragmentHost(new FragmentHostImpl()); 1109 } 1110 1111 ft.commit(); 1112 } else { 1113 mHeadersSupportFragment = (HeadersSupportFragment) getChildFragmentManager() 1114 .findFragmentById(R.id.browse_headers_dock); 1115 mMainFragment = getChildFragmentManager().findFragmentById(R.id.scale_frame); 1116 mMainFragmentAdapter = ((MainFragmentAdapterProvider)mMainFragment) 1117 .getMainFragmentAdapter(); 1118 mMainFragmentAdapter.setFragmentHost(new FragmentHostImpl()); 1119 1120 mIsPageRow = savedInstanceState != null ? 1121 savedInstanceState.getBoolean(IS_PAGE_ROW, false) : false; 1122 1123 mSelectedPosition = savedInstanceState != null ? 1124 savedInstanceState.getInt(CURRENT_SELECTED_POSITION, 0) : 0; 1125 1126 if (!mIsPageRow) { 1127 if (mMainFragment instanceof MainFragmentRowsAdapterProvider) { 1128 mMainFragmentRowsAdapter = ((MainFragmentRowsAdapterProvider) mMainFragment) 1129 .getMainFragmentRowsAdapter(); 1130 } else { 1131 mMainFragmentRowsAdapter = null; 1132 } 1133 } else { 1134 mMainFragmentRowsAdapter = null; 1135 } 1136 } 1137 1138 mHeadersSupportFragment.setHeadersGone(!mCanShowHeaders); 1139 if (mHeaderPresenterSelector != null) { 1140 mHeadersSupportFragment.setPresenterSelector(mHeaderPresenterSelector); 1141 } 1142 mHeadersSupportFragment.setAdapter(mAdapter); 1143 mHeadersSupportFragment.setOnHeaderViewSelectedListener(mHeaderViewSelectedListener); 1144 mHeadersSupportFragment.setOnHeaderClickedListener(mHeaderClickedListener); 1145 1146 View root = inflater.inflate(R.layout.lb_browse_fragment, container, false); 1147 1148 getProgressBarManager().setRootView((ViewGroup)root); 1149 1150 mBrowseFrame = (BrowseFrameLayout) root.findViewById(R.id.browse_frame); 1151 mBrowseFrame.setOnChildFocusListener(mOnChildFocusListener); 1152 mBrowseFrame.setOnFocusSearchListener(mOnFocusSearchListener); 1153 1154 installTitleView(inflater, mBrowseFrame, savedInstanceState); 1155 1156 mScaleFrameLayout = (ScaleFrameLayout) root.findViewById(R.id.scale_frame); 1157 mScaleFrameLayout.setPivotX(0); 1158 mScaleFrameLayout.setPivotY(mContainerListAlignTop); 1159 1160 setupMainFragment(); 1161 1162 if (mBrandColorSet) { 1163 mHeadersSupportFragment.setBackgroundColor(mBrandColor); 1164 } 1165 1166 mSceneWithHeaders = TransitionHelper.createScene(mBrowseFrame, new Runnable() { 1167 @Override 1168 public void run() { 1169 showHeaders(true); 1170 } 1171 }); 1172 mSceneWithoutHeaders = TransitionHelper.createScene(mBrowseFrame, new Runnable() { 1173 @Override 1174 public void run() { 1175 showHeaders(false); 1176 } 1177 }); 1178 mSceneAfterEntranceTransition = TransitionHelper.createScene(mBrowseFrame, new Runnable() { 1179 @Override 1180 public void run() { 1181 setEntranceTransitionEndState(); 1182 } 1183 }); 1184 1185 return root; 1186 } 1187 1188 private void setupMainFragment() { 1189 if (mMainFragmentRowsAdapter != null) { 1190 mMainFragmentRowsAdapter.setAdapter(mAdapter); 1191 mMainFragmentRowsAdapter.setOnItemViewSelectedListener( 1192 new MainFragmentItemViewSelectedListener(mMainFragmentRowsAdapter)); 1193 mMainFragmentRowsAdapter.setOnItemViewClickedListener(mOnItemViewClickedListener); 1194 } 1195 } 1196 1197 @Override 1198 boolean isReadyForPrepareEntranceTransition() { 1199 return mMainFragment != null && mMainFragment.getView() != null; 1200 } 1201 1202 @Override 1203 boolean isReadyForStartEntranceTransition() { 1204 return mMainFragment != null && mMainFragment.getView() != null 1205 && (!mIsPageRow || mMainFragmentAdapter.mFragmentHost.mDataReady); 1206 } 1207 1208 private void createHeadersTransition() { 1209 mHeadersTransition = TransitionHelper.loadTransition(getActivity(), 1210 mShowingHeaders ? 1211 R.transition.lb_browse_headers_in : R.transition.lb_browse_headers_out); 1212 1213 TransitionHelper.addTransitionListener(mHeadersTransition, new TransitionListener() { 1214 @Override 1215 public void onTransitionStart(Object transition) { 1216 } 1217 @Override 1218 public void onTransitionEnd(Object transition) { 1219 mHeadersTransition = null; 1220 if (mMainFragmentAdapter != null) { 1221 mMainFragmentAdapter.onTransitionEnd(); 1222 if (!mShowingHeaders && mMainFragment != null) { 1223 View mainFragmentView = mMainFragment.getView(); 1224 if (mainFragmentView != null && !mainFragmentView.hasFocus()) { 1225 mainFragmentView.requestFocus(); 1226 } 1227 } 1228 } 1229 if (mHeadersSupportFragment != null) { 1230 mHeadersSupportFragment.onTransitionEnd(); 1231 if (mShowingHeaders) { 1232 VerticalGridView headerGridView = mHeadersSupportFragment.getVerticalGridView(); 1233 if (headerGridView != null && !headerGridView.hasFocus()) { 1234 headerGridView.requestFocus(); 1235 } 1236 } 1237 } 1238 1239 // Animate TitleView once header animation is complete. 1240 updateTitleViewVisibility(); 1241 1242 if (mBrowseTransitionListener != null) { 1243 mBrowseTransitionListener.onHeadersTransitionStop(mShowingHeaders); 1244 } 1245 } 1246 }); 1247 } 1248 1249 void updateTitleViewVisibility() { 1250 if (!mShowingHeaders) { 1251 boolean showTitleView; 1252 if (mIsPageRow && mMainFragmentAdapter != null) { 1253 // page fragment case: 1254 showTitleView = mMainFragmentAdapter.mFragmentHost.mShowTitleView; 1255 } else { 1256 // regular row view case: 1257 showTitleView = isFirstRowWithContent(mSelectedPosition); 1258 } 1259 if (showTitleView) { 1260 showTitle(TitleViewAdapter.FULL_VIEW_VISIBLE); 1261 } else { 1262 showTitle(false); 1263 } 1264 } else { 1265 // when HeaderFragment is showing, showBranding and showSearch are slightly different 1266 boolean showBranding; 1267 boolean showSearch; 1268 if (mIsPageRow && mMainFragmentAdapter != null) { 1269 showBranding = mMainFragmentAdapter.mFragmentHost.mShowTitleView; 1270 } else { 1271 showBranding = isFirstRowWithContent(mSelectedPosition); 1272 } 1273 showSearch = isFirstRowWithContentOrPageRow(mSelectedPosition); 1274 int flags = 0; 1275 if (showBranding) flags |= TitleViewAdapter.BRANDING_VIEW_VISIBLE; 1276 if (showSearch) flags |= TitleViewAdapter.SEARCH_VIEW_VISIBLE; 1277 if (flags != 0) { 1278 showTitle(flags); 1279 } else { 1280 showTitle(false); 1281 } 1282 } 1283 } 1284 1285 boolean isFirstRowWithContentOrPageRow(int rowPosition) { 1286 if (mAdapter == null || mAdapter.size() == 0) { 1287 return true; 1288 } 1289 for (int i = 0; i < mAdapter.size(); i++) { 1290 final Row row = (Row) mAdapter.get(i); 1291 if (row.isRenderedAsRowView() || row instanceof PageRow) { 1292 return rowPosition == i; 1293 } 1294 } 1295 return true; 1296 } 1297 1298 boolean isFirstRowWithContent(int rowPosition) { 1299 if (mAdapter == null || mAdapter.size() == 0) { 1300 return true; 1301 } 1302 for (int i = 0; i < mAdapter.size(); i++) { 1303 final Row row = (Row) mAdapter.get(i); 1304 if (row.isRenderedAsRowView()) { 1305 return rowPosition == i; 1306 } 1307 } 1308 return true; 1309 } 1310 1311 /** 1312 * Sets the {@link PresenterSelector} used to render the row headers. 1313 * 1314 * @param headerPresenterSelector The PresenterSelector that will determine 1315 * the Presenter for each row header. 1316 */ 1317 public void setHeaderPresenterSelector(PresenterSelector headerPresenterSelector) { 1318 mHeaderPresenterSelector = headerPresenterSelector; 1319 if (mHeadersSupportFragment != null) { 1320 mHeadersSupportFragment.setPresenterSelector(mHeaderPresenterSelector); 1321 } 1322 } 1323 1324 private void setHeadersOnScreen(boolean onScreen) { 1325 MarginLayoutParams lp; 1326 View containerList; 1327 containerList = mHeadersSupportFragment.getView(); 1328 lp = (MarginLayoutParams) containerList.getLayoutParams(); 1329 lp.setMarginStart(onScreen ? 0 : -mContainerListMarginStart); 1330 containerList.setLayoutParams(lp); 1331 } 1332 1333 private void showHeaders(boolean show) { 1334 if (DEBUG) Log.v(TAG, "showHeaders " + show); 1335 mHeadersSupportFragment.setHeadersEnabled(show); 1336 setHeadersOnScreen(show); 1337 expandMainFragment(!show); 1338 } 1339 1340 private void expandMainFragment(boolean expand) { 1341 MarginLayoutParams params = (MarginLayoutParams) mScaleFrameLayout.getLayoutParams(); 1342 params.setMarginStart(!expand ? mContainerListMarginStart : 0); 1343 mScaleFrameLayout.setLayoutParams(params); 1344 mMainFragmentAdapter.setExpand(expand); 1345 1346 setMainFragmentAlignment(); 1347 final float scaleFactor = !expand 1348 && mMainFragmentScaleEnabled 1349 && mMainFragmentAdapter.isScalingEnabled() ? mScaleFactor : 1; 1350 mScaleFrameLayout.setLayoutScaleY(scaleFactor); 1351 mScaleFrameLayout.setChildScale(scaleFactor); 1352 } 1353 1354 private HeadersSupportFragment.OnHeaderClickedListener mHeaderClickedListener = 1355 new HeadersSupportFragment.OnHeaderClickedListener() { 1356 @Override 1357 public void onHeaderClicked(RowHeaderPresenter.ViewHolder viewHolder, Row row) { 1358 if (!mCanShowHeaders || !mShowingHeaders || isInHeadersTransition()) { 1359 return; 1360 } 1361 startHeadersTransitionInternal(false); 1362 mMainFragment.getView().requestFocus(); 1363 } 1364 }; 1365 1366 class MainFragmentItemViewSelectedListener implements OnItemViewSelectedListener { 1367 MainFragmentRowsAdapter mMainFragmentRowsAdapter; 1368 1369 public MainFragmentItemViewSelectedListener(MainFragmentRowsAdapter fragmentRowsAdapter) { 1370 mMainFragmentRowsAdapter = fragmentRowsAdapter; 1371 } 1372 1373 @Override 1374 public void onItemSelected(Presenter.ViewHolder itemViewHolder, Object item, 1375 RowPresenter.ViewHolder rowViewHolder, Row row) { 1376 int position = mMainFragmentRowsAdapter.getSelectedPosition(); 1377 if (DEBUG) Log.v(TAG, "row selected position " + position); 1378 onRowSelected(position); 1379 if (mExternalOnItemViewSelectedListener != null) { 1380 mExternalOnItemViewSelectedListener.onItemSelected(itemViewHolder, item, 1381 rowViewHolder, row); 1382 } 1383 } 1384 }; 1385 1386 private HeadersSupportFragment.OnHeaderViewSelectedListener mHeaderViewSelectedListener = 1387 new HeadersSupportFragment.OnHeaderViewSelectedListener() { 1388 @Override 1389 public void onHeaderSelected(RowHeaderPresenter.ViewHolder viewHolder, Row row) { 1390 int position = mHeadersSupportFragment.getSelectedPosition(); 1391 if (DEBUG) Log.v(TAG, "header selected position " + position); 1392 onRowSelected(position); 1393 } 1394 }; 1395 1396 private void onRowSelected(int position) { 1397 if (position != mSelectedPosition) { 1398 mSetSelectionRunnable.post( 1399 position, SetSelectionRunnable.TYPE_INTERNAL_SYNC, true); 1400 } 1401 } 1402 1403 private void setSelection(int position, boolean smooth) { 1404 if (position == NO_POSITION) { 1405 return; 1406 } 1407 1408 mHeadersSupportFragment.setSelectedPosition(position, smooth); 1409 replaceMainFragment(position); 1410 1411 if (mMainFragmentRowsAdapter != null) { 1412 mMainFragmentRowsAdapter.setSelectedPosition(position, smooth); 1413 } 1414 mSelectedPosition = position; 1415 1416 updateTitleViewVisibility(); 1417 } 1418 1419 private void replaceMainFragment(int position) { 1420 if (createMainFragment(mAdapter, position)) { 1421 swapToMainFragment(); 1422 expandMainFragment(!(mCanShowHeaders && mShowingHeaders)); 1423 setupMainFragment(); 1424 performPendingStates(); 1425 } 1426 } 1427 1428 private void swapToMainFragment() { 1429 final VerticalGridView gridView = mHeadersSupportFragment.getVerticalGridView(); 1430 if (isShowingHeaders() && gridView != null 1431 && gridView.getScrollState() != RecyclerView.SCROLL_STATE_IDLE) { 1432 // if user is scrolling HeadersSupportFragment, swap to empty fragment and wait scrolling 1433 // finishes. 1434 getChildFragmentManager().beginTransaction() 1435 .replace(R.id.scale_frame, new Fragment()).commit(); 1436 gridView.addOnScrollListener(new RecyclerView.OnScrollListener() { 1437 @Override 1438 public void onScrollStateChanged(RecyclerView recyclerView, int newState) { 1439 if (newState == RecyclerView.SCROLL_STATE_IDLE) { 1440 gridView.removeOnScrollListener(this); 1441 FragmentManager fm = getChildFragmentManager(); 1442 Fragment currentFragment = fm.findFragmentById(R.id.scale_frame); 1443 if (currentFragment != mMainFragment) { 1444 fm.beginTransaction().replace(R.id.scale_frame, mMainFragment).commit(); 1445 } 1446 } 1447 } 1448 }); 1449 } else { 1450 // Otherwise swap immediately 1451 getChildFragmentManager().beginTransaction() 1452 .replace(R.id.scale_frame, mMainFragment).commit(); 1453 } 1454 } 1455 1456 /** 1457 * Sets the selected row position with smooth animation. 1458 */ 1459 public void setSelectedPosition(int position) { 1460 setSelectedPosition(position, true); 1461 } 1462 1463 /** 1464 * Gets position of currently selected row. 1465 * @return Position of currently selected row. 1466 */ 1467 public int getSelectedPosition() { 1468 return mSelectedPosition; 1469 } 1470 1471 /** 1472 * Sets the selected row position. 1473 */ 1474 public void setSelectedPosition(int position, boolean smooth) { 1475 mSetSelectionRunnable.post( 1476 position, SetSelectionRunnable.TYPE_USER_REQUEST, smooth); 1477 } 1478 1479 /** 1480 * Selects a Row and perform an optional task on the Row. For example 1481 * <code>setSelectedPosition(10, true, new ListRowPresenterSelectItemViewHolderTask(5))</code> 1482 * scrolls to 11th row and selects 6th item on that row. The method will be ignored if 1483 * RowsSupportFragment has not been created (i.e. before {@link #onCreateView(LayoutInflater, 1484 * ViewGroup, Bundle)}). 1485 * 1486 * @param rowPosition Which row to select. 1487 * @param smooth True to scroll to the row, false for no animation. 1488 * @param rowHolderTask Optional task to perform on the Row. When the task is not null, headers 1489 * fragment will be collapsed. 1490 */ 1491 public void setSelectedPosition(int rowPosition, boolean smooth, 1492 final Presenter.ViewHolderTask rowHolderTask) { 1493 if (mMainFragmentAdapterRegistry == null) { 1494 return; 1495 } 1496 if (rowHolderTask != null) { 1497 startHeadersTransition(false); 1498 } 1499 if (mMainFragmentRowsAdapter != null) { 1500 mMainFragmentRowsAdapter.setSelectedPosition(rowPosition, smooth, rowHolderTask); 1501 } 1502 } 1503 1504 @Override 1505 public void onStart() { 1506 super.onStart(); 1507 mHeadersSupportFragment.setAlignment(mContainerListAlignTop); 1508 setMainFragmentAlignment(); 1509 1510 if (mCanShowHeaders && mShowingHeaders && mHeadersSupportFragment.getView() != null) { 1511 mHeadersSupportFragment.getView().requestFocus(); 1512 } else if ((!mCanShowHeaders || !mShowingHeaders) 1513 && mMainFragment.getView() != null) { 1514 mMainFragment.getView().requestFocus(); 1515 } 1516 1517 if (mCanShowHeaders) { 1518 showHeaders(mShowingHeaders); 1519 } 1520 1521 if (isEntranceTransitionEnabled()) { 1522 setEntranceTransitionStartState(); 1523 } 1524 } 1525 1526 private void onExpandTransitionStart(boolean expand, final Runnable callback) { 1527 if (expand) { 1528 callback.run(); 1529 return; 1530 } 1531 // Run a "pre" layout when we go non-expand, in order to get the initial 1532 // positions of added rows. 1533 new ExpandPreLayout(callback, mMainFragmentAdapter, getView()).execute(); 1534 } 1535 1536 private void setMainFragmentAlignment() { 1537 int alignOffset = mContainerListAlignTop; 1538 if (mMainFragmentScaleEnabled 1539 && mMainFragmentAdapter.isScalingEnabled() 1540 && mShowingHeaders) { 1541 alignOffset = (int) (alignOffset / mScaleFactor + 0.5f); 1542 } 1543 mMainFragmentAdapter.setAlignment(alignOffset); 1544 } 1545 1546 /** 1547 * Enables/disables headers transition on back key support. This is enabled by 1548 * default. The BrowseSupportFragment will add a back stack entry when headers are 1549 * showing. Running a headers transition when the back key is pressed only 1550 * works when the headers state is {@link #HEADERS_ENABLED} or 1551 * {@link #HEADERS_HIDDEN}. 1552 * <p> 1553 * NOTE: If an Activity has its own onBackPressed() handling, you must 1554 * disable this feature. You may use {@link #startHeadersTransition(boolean)} 1555 * and {@link BrowseTransitionListener} in your own back stack handling. 1556 */ 1557 public final void setHeadersTransitionOnBackEnabled(boolean headersBackStackEnabled) { 1558 mHeadersBackStackEnabled = headersBackStackEnabled; 1559 } 1560 1561 /** 1562 * Returns true if headers transition on back key support is enabled. 1563 */ 1564 public final boolean isHeadersTransitionOnBackEnabled() { 1565 return mHeadersBackStackEnabled; 1566 } 1567 1568 private void readArguments(Bundle args) { 1569 if (args == null) { 1570 return; 1571 } 1572 if (args.containsKey(ARG_TITLE)) { 1573 setTitle(args.getString(ARG_TITLE)); 1574 } 1575 if (args.containsKey(ARG_HEADERS_STATE)) { 1576 setHeadersState(args.getInt(ARG_HEADERS_STATE)); 1577 } 1578 } 1579 1580 /** 1581 * Sets the state for the headers column in the browse fragment. Must be one 1582 * of {@link #HEADERS_ENABLED}, {@link #HEADERS_HIDDEN}, or 1583 * {@link #HEADERS_DISABLED}. 1584 * 1585 * @param headersState The state of the headers for the browse fragment. 1586 */ 1587 public void setHeadersState(int headersState) { 1588 if (headersState < HEADERS_ENABLED || headersState > HEADERS_DISABLED) { 1589 throw new IllegalArgumentException("Invalid headers state: " + headersState); 1590 } 1591 if (DEBUG) Log.v(TAG, "setHeadersState " + headersState); 1592 1593 if (headersState != mHeadersState) { 1594 mHeadersState = headersState; 1595 switch (headersState) { 1596 case HEADERS_ENABLED: 1597 mCanShowHeaders = true; 1598 mShowingHeaders = true; 1599 break; 1600 case HEADERS_HIDDEN: 1601 mCanShowHeaders = true; 1602 mShowingHeaders = false; 1603 break; 1604 case HEADERS_DISABLED: 1605 mCanShowHeaders = false; 1606 mShowingHeaders = false; 1607 break; 1608 default: 1609 Log.w(TAG, "Unknown headers state: " + headersState); 1610 break; 1611 } 1612 if (mHeadersSupportFragment != null) { 1613 mHeadersSupportFragment.setHeadersGone(!mCanShowHeaders); 1614 } 1615 } 1616 } 1617 1618 /** 1619 * Returns the state of the headers column in the browse fragment. 1620 */ 1621 public int getHeadersState() { 1622 return mHeadersState; 1623 } 1624 1625 @Override 1626 protected Object createEntranceTransition() { 1627 return TransitionHelper.loadTransition(getActivity(), 1628 R.transition.lb_browse_entrance_transition); 1629 } 1630 1631 @Override 1632 protected void runEntranceTransition(Object entranceTransition) { 1633 TransitionHelper.runTransition(mSceneAfterEntranceTransition, entranceTransition); 1634 } 1635 1636 @Override 1637 protected void onEntranceTransitionPrepare() { 1638 mHeadersSupportFragment.onTransitionPrepare(); 1639 // setEntranceTransitionStartState() might be called when mMainFragment is null, 1640 // make sure it is called. 1641 mMainFragmentAdapter.setEntranceTransitionState(false); 1642 mMainFragmentAdapter.onTransitionPrepare(); 1643 } 1644 1645 @Override 1646 protected void onEntranceTransitionStart() { 1647 mHeadersSupportFragment.onTransitionStart(); 1648 mMainFragmentAdapter.onTransitionStart(); 1649 } 1650 1651 @Override 1652 protected void onEntranceTransitionEnd() { 1653 if (mMainFragmentAdapter != null) { 1654 mMainFragmentAdapter.onTransitionEnd(); 1655 } 1656 1657 if (mHeadersSupportFragment != null) { 1658 mHeadersSupportFragment.onTransitionEnd(); 1659 } 1660 } 1661 1662 void setSearchOrbViewOnScreen(boolean onScreen) { 1663 View searchOrbView = getTitleViewAdapter().getSearchAffordanceView(); 1664 if (searchOrbView != null) { 1665 MarginLayoutParams lp = (MarginLayoutParams) searchOrbView.getLayoutParams(); 1666 lp.setMarginStart(onScreen ? 0 : -mContainerListMarginStart); 1667 searchOrbView.setLayoutParams(lp); 1668 } 1669 } 1670 1671 void setEntranceTransitionStartState() { 1672 setHeadersOnScreen(false); 1673 setSearchOrbViewOnScreen(false); 1674 mMainFragmentAdapter.setEntranceTransitionState(false); 1675 } 1676 1677 void setEntranceTransitionEndState() { 1678 setHeadersOnScreen(mShowingHeaders); 1679 setSearchOrbViewOnScreen(true); 1680 mMainFragmentAdapter.setEntranceTransitionState(true); 1681 } 1682 1683 private class ExpandPreLayout implements ViewTreeObserver.OnPreDrawListener { 1684 1685 private final View mView; 1686 private final Runnable mCallback; 1687 private int mState; 1688 private MainFragmentAdapter mainFragmentAdapter; 1689 1690 final static int STATE_INIT = 0; 1691 final static int STATE_FIRST_DRAW = 1; 1692 final static int STATE_SECOND_DRAW = 2; 1693 1694 ExpandPreLayout(Runnable callback, MainFragmentAdapter adapter, View view) { 1695 mView = view; 1696 mCallback = callback; 1697 mainFragmentAdapter = adapter; 1698 } 1699 1700 void execute() { 1701 mView.getViewTreeObserver().addOnPreDrawListener(this); 1702 mainFragmentAdapter.setExpand(false); 1703 mState = STATE_INIT; 1704 } 1705 1706 @Override 1707 public boolean onPreDraw() { 1708 if (getView() == null || getActivity() == null) { 1709 mView.getViewTreeObserver().removeOnPreDrawListener(this); 1710 return true; 1711 } 1712 if (mState == STATE_INIT) { 1713 mainFragmentAdapter.setExpand(true); 1714 mState = STATE_FIRST_DRAW; 1715 } else if (mState == STATE_FIRST_DRAW) { 1716 mCallback.run(); 1717 mView.getViewTreeObserver().removeOnPreDrawListener(this); 1718 mState = STATE_SECOND_DRAW; 1719 } 1720 return false; 1721 } 1722 } 1723} 1724