Как разместить RecyclerView внутри NestedScrollView?

С созданием NestedScrollView вы можете поместить прокрутку в другое прокручиваемое представление, если они правильно реализуют NestedScrollingChild и NestedScrollingParent .

(Это неплохой шаблон дизайна «Янь-Лейк» (от Google) на самом деле рекомендует разместить RecyclerView внутри вложенного просмотра: plus.google.com/u/0/+AndroidDevelopers/posts/9kZ3SsXdT2T »)

Я хочу добавить RecyclerView внутри NestedScrollView и, к счастью, RecyclerView реализует NestedScrollingChild, поэтому вы можете поместить его внутри NestedScrollView .

 public class RecyclerView extends ViewGroup implements ScrollingView, NestedScrollingChild 

Я прочитал эти сообщения:

Как использовать RecyclerView внутри NestedScrollView?

NestedScrolling с помощью NestedScrollView, RecyclerView (по горизонтали) внутри координатораLayout

Но проблема с большинством голосующих решений заключается в том, что он вызывает все элементы RecyclerView например, если это бесконечный RecyclerView, и когда пользователь достигает конца списка, который вы хотите сделать сетевым запросом, то с этим решением вызовы RecyclerView сервер, потому что он автоматически достигает последнего элемента RecyclerView .

В любом случае, как установить параметр, чтобы я мог поместить RecyclerView внутри NestedScrollView . (На самом деле я хочу поместить группу представлений, такую ​​как framelayout или relativelayout, в виде одного дочернего элемента nestedscrollview, а затем я хочу включить recyclerview внутри framelayout или relativelayout)

Когда я кладу RecyclerView внутри NestedScrollView ничего не NestedScrollView .


Чтобы создать образец проекта, вы можете использовать cheesesquare и изменить CheeseDetailActivity чтобы иметь RecyclerView.


Хотя ответ BNK неверен, но BNK много пробовал. Поэтому я награждаю его щедростью. Все еще ищут хорошее решение ….

Следующий мой новый обновленный ответ:

                  

В работе:

  RecyclerViewAdapter recyclerViewAdapter = new RecyclerViewAdapter(true); // true: with header RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview); final MyLinearLayoutManager layoutManager = new MyLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false, getScreenHeight(this)); // final CustomLinearLayoutManager layoutManager = new CustomLinearLayoutManager(this, LinearLayoutManager.VERTICAL, false); recyclerView.setLayoutManager(layoutManager); recyclerView.setAdapter(recyclerViewAdapter); // recyclerView.setNestedScrollingEnabled(false); // Disables scrolling for RecyclerView, however, CustomLinearLayoutManager used instead of MyLinearLayoutManager 

Я также обновил образец проекта My GitHub

Скриншот:

введите описание изображения здесь


Вот решение для вызова сервера только тогда, когда вам действительно необходимо загрузить больше данных. Таким образом, вы можете разместить бесконечное RecyclerView и многие другие виды внутри NestedScrollView. Для меня это хорошо работает.

1. Создайте class EndlessParentScrollListener для обработки событий прокрутки из NestedSrollView.

 public abstract class EndlessParentScrollListener implements NestedScrollView.OnScrollChangeListener { // The current offset index of data you have loaded private int currentPage = 0; // The total number of items in the dataset after the last load private int previousTotalItemCount = 0; // True if we are still waiting for the last set of data to load. private boolean loading = true; // Sets the starting page index private int startingPageIndex = 0; // The minimum amount of pixels to have below your current scroll position // before loading more. private int visibleThresholdDistance = 300; RecyclerView.LayoutManager mLayoutManager; public EndlessParentScrollListener(RecyclerView.LayoutManager layoutManager) { this.mLayoutManager = layoutManager; } @Override public void onScrollChange(NestedScrollView scrollView, int x, int y, int oldx, int oldy) { // We take the last son in the scrollview View view = scrollView.getChildAt(scrollView.getChildCount() - 1); int distanceToEnd = (view.getBottom() - (scrollView.getHeight() + scrollView.getScrollY())); int totalItemCount = mLayoutManager.getItemCount(); // If the total item count is zero and the previous isn't, assume the // list is invalidated and should be reset back to initial state if (totalItemCount < previousTotalItemCount) { this.currentPage = this.startingPageIndex; this.previousTotalItemCount = totalItemCount; if (totalItemCount == 0) { this.loading = true; } } // If it's still loading, we check to see if the dataset count has // changed, if so we conclude it has finished loading and update the current page // number and total item count. if (loading && (totalItemCount > previousTotalItemCount)) { loading = false; previousTotalItemCount = totalItemCount; } // If it isn't currently loading, we check to see if we have breached // the visibleThreshold and need to reload more data. // If we do need to reload some more data, we execute onLoadMore to fetch the data. // threshold should reflect how many total columns there are too if (!loading && distanceToEnd <= visibleThresholdDistance) { currentPage++; onLoadMore(currentPage, totalItemCount); loading = true; } } // Defines the process for actually loading more data based on page public abstract void onLoadMore(int page, int totalItemsCount); } 

2. Установить прослушиватель

 private void initRecycler() { //TODO init recycler adapter here recycler.setNestedScrollingEnabled(false); LinearLayoutManager _layoutManager = new LinearLayoutManager(this); recycler.setLayoutManager(_layoutManager); NestedScrollView scrollView = (NestedScrollView) findViewById(R.id.scrollView); scrollView.setOnScrollChangeListener(new EndlessParentScrollListener(_layoutManager) { @Override public void onLoadMore(int page, int totalItemsCount) { if (loadedItemCount < serverItemsCount) customLoadMoreDataFromApi(); } }); customLoadMoreDataFromApi(); } 

Короткий xml, если кто-то найдет это полезным:

   ...          

Таким образом, RetyclerView непосредственно внутри NestedScrollView будет, к сожалению, ничего не показывать. Тем не менее, есть способ поместить recyclerview внутри NestedScrollView косвенно – просто используйте frameLayout в качестве третьей стороны для хранения вашего recyclerview.

Это framelayout, который содержит вложенный recyclerview в вашем classе активности :

      

Поместите fragment в рамку (код находится внутри classа активности ):

  ExampleFragment exampleFragment = new ExampleFragment(); FragmentManager fm = getSupportFragmentManager(); FragmentTransaction ft = fm.beginTransaction(); ft.add(R.id.container, exampleFragment); ft.commit(); 

В вашем примере «Фрагмент» вы можете поместить свой recyclerview.

      

Это код fragmentа :

 @Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { super.onCreateView(inflater, container, savedInstanceState); llLayout = (RelativeLayout) inflater.inflate(R.layout.example_fragment_layout, container, false); mRecyclerView = (RecyclerView) llLayout.findViewById(R.id.my_recycler_view); 

Ниже приведен макет CheeseSquare XML, который должен иметь:

              
  • настраиваемый метод getView адаптера listview, который вызывается несколько раз и не имеет когерентного порядка
  • Можем ли мы использовать детектор жестов масштаба для увеличения зума в Android?
  • Диалог для выбора изображения из галереи или с камеры
  • Android: При каких обстоятельствах будет вызываться диалог, вызывающий onPause ()?
  • Как определить, когда пользователь подключает гарнитуру на устройстве Android? (Напротив ACTION_AUDIO_BECOMING_NOISY)
  • Удаление вызова журнала с помощью proguard
  • Проверка наличия определенного значения в базе данных firebase
  • Android PendingIntent, не получаемый BroadcastReceiver
  • Не удалось разрешить целевой «android-XX»
  • Неправильные координаты из getLocationOnScreen / getLocationInWindow
  • Как обрабатывать OutOfMemoryError
  • Interesting Posts

    Десятичный разделитель запятой (‘,’) с номеромDecimal inputType в EditText

    Применить формулу VLOOKUP к нескольким листам

    Как рассчитать возраст человека на Java?

    Как я могу указать свойства системы в конфигурации Tomcat при запуске?

    Каковы размеры операндов tword, oword и yword?

    почему менеджер безопасности Java не запрещает ни создавать новый Thread (), ни запускать его?

    Редактирование заявления о суммировании автоматической суммы

    Ошибка шрифта Helvetica Neue – помеченные символы в Google Chrome для Mac

    Как конвертировать простой .NET-проект в переносимый exe с помощью Mono и mkbundle?

    Какова наилучшая практика для работы с паролями в репозиториях git?

    Как добавить опцию загрузки съемного диска (USB-накопителя) в меню настроек загрузки BIOS?

    Что делает три точки в ReactJS

    Google Spreadsheet = Фильтр в Excel

    Отправка сообщений между двумя объектами JPanel

    Что такое проверенные исключения в Java / C #?

    Давайте будем гением компьютера.