如何用下一页“10 项”填充标题和网格布局
Posted
技术标签:
【中文标题】如何用下一页“10 项”填充标题和网格布局【英文标题】:How to fill title and grid layouts with the next page "10 items" 【发布时间】:2021-06-18 17:33:27 【问题描述】:在我的应用中,我有四种布局,"Card List"、"Card Magazine"、"Title" 和 " Grid”,我制作了选项菜单以允许用户从选项菜单“更改布局”中更改它,这里发生的问题是第一次运行应用程序时选择标题或网格布局时,它只显示第一页“10 项”结果来自改造电话
要联系看到这个question
在这个应用程序的旧版本“当我使用活动时”中,我用标题和网格视图持有者上的这行代码解决了这个问题
if(position == getItemCount() -1)
if(context instanceof MainActivity)
((MainActivity)context).getMainPagePosts();
但是在这个版本中我使用了片段,所以当我试图解决它时,我创建了名为 "WhichFragmentCalled" 的接口并将片段和 viewHolder 作为参数提供给它
public interface WhichFragmentCalled
void whichFragmentAndViewModel(Fragment fragment, PostViewModel postViewModel);
然后我像这样在适配器和片段中使用它
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
WhichFragmentCalled whichFragmentCalled = adapter;
whichFragmentCalled.whichFragmentAndViewModel(this,postViewModel);
让适配器实现这个接口,这里是完整的PostAdapter代码
public class PostAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> implements WhichFragmentCalled
private Context context;
private List<Item> items;
private static final int CARD = 0;
private static final int CARD_MAGAZINE = 1;
private static final int TITLE = 2;
private static final int GRID = 3;
private static final int SDK_VERSION = Build.VERSION.SDK_INT;
public static final String TAG = "POST ADAPTER";
private int viewType;
private int position;
private Fragment fragment;
private PostViewModel postViewModel;
public PostAdapter(Context context, List<Item> items)
this.context = context;
this.items = items;
public void setViewType(int viewType)
this.viewType = viewType;
notifyDataSetChanged();
public int getViewType()
return this.viewType;
@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType)
LayoutInflater inflater = LayoutInflater.from(context);
View view;
if (this.viewType == CARD)
view = inflater.inflate(R.layout.card, parent, false);
return new CardViewHolder(view);
else if (this.viewType == CARD_MAGAZINE)
view = inflater.inflate(R.layout.card_magazine, parent, false);
return new CardMagazineViewHolder(view);
else if (this.viewType == TITLE)
if(SDK_VERSION < Build.VERSION_CODES.LOLLIPOP)
view = inflater.inflate(R.layout.title_layout_v15,parent,false);
else
view = inflater.inflate(R.layout.title_layout, parent, false);
return new TitleViewHolder(view);
else
if(SDK_VERSION < Build.VERSION_CODES.LOLLIPOP)
view = inflater.inflate(R.layout.grid_layout_v15,parent,false);
else
view = inflater.inflate(R.layout.grid_layout, parent, false);
return new GridViewHolder(view);
@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position)
this.position = position;
int itemType = getViewType();
Item item = items.get(holder.getAdapterPosition());
final Document document = Jsoup.parse(item.getContent());
final Elements elements = document.select("img");
// Log.e("IMAGE", document.getAllElements().select("img").get(0).attr("src"));
Date date = new Date();
SimpleDateFormat format = new SimpleDateFormat
("yyyy-MM-dd'T'HH:mm:ssZ", Locale.getDefault());
Intent intent = new Intent(context, DetailsActivity.class);
switch (itemType)
case CARD:
if (holder instanceof CardViewHolder)
CardViewHolder cardViewHolder = (CardViewHolder) holder;
cardViewHolder.postTitle.setText(item.getTitle());
try
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(cardViewHolder.postImage);
catch (IndexOutOfBoundsException e)
cardViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
cardViewHolder.postDescription.setText(document.text());
try
date = format.parse(items.get(position).getPublished());
catch (ParseException e)
e.printStackTrace();
PrettyTime prettyTime = new PrettyTime();
cardViewHolder.postDate.setText(prettyTime.format(date));
cardViewHolder.itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility = 0;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video"))
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
if (youtubeThumbnailImageSrc.isEmpty())
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
else
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
);
break;
case CARD_MAGAZINE:
if (holder instanceof CardMagazineViewHolder)
CardMagazineViewHolder cardMagazineViewHolder = (CardMagazineViewHolder) holder;
cardMagazineViewHolder.postTitle.setText(item.getTitle());
try
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(cardMagazineViewHolder.postImage);
catch (IndexOutOfBoundsException e)
cardMagazineViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
try
date = format.parse(items.get(position).getPublished());
catch (ParseException e)
e.printStackTrace();
PrettyTime prettyTime = new PrettyTime();
cardMagazineViewHolder.postDate.setText(prettyTime.format(date));
cardMagazineViewHolder.itemView.setOnClickListener(new View.OnClickListener()
@Override
public void onClick(View view)
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility = 0;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video"))
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
if (youtubeThumbnailImageSrc.isEmpty())
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
else
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
);
break;
case TITLE:
if (holder instanceof TitleViewHolder)
TitleViewHolder titleViewHolder = (TitleViewHolder) holder;
titleViewHolder.postTitle.setText(item.getTitle());
Log.d("TITLE", "title layout called");
try
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(titleViewHolder.postImage);
catch (IndexOutOfBoundsException e)
titleViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
titleViewHolder.itemView.setOnClickListener(view ->
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility = 0;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video"))
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
if (youtubeThumbnailImageSrc.isEmpty())
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
else
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
);
break;
case GRID:
if (holder instanceof GridViewHolder)
GridViewHolder gridViewHolder = (GridViewHolder) holder;
gridViewHolder.postTitle.setText(item.getTitle());
try
Log.e("IMAGE", elements.get(0).attr("src"));
Glide.with(context).load(elements.get(0).attr("src"))
.into(gridViewHolder.postImage);
catch (IndexOutOfBoundsException e)
gridViewHolder.postImage.setImageResource(R.mipmap.ic_launcher);
Log.e(TAG,e.toString());
gridViewHolder.itemView.setOnClickListener(view ->
intent.putExtra("url", item.getUrl());
intent.putExtra("title", item.getTitle());
intent.putExtra("content", item.getContent());
int youtubeThumbnailImagesetVisibility;
Element element = document.body();
String youtubeThumbnailImageSrc = "";
String youTubeLink = "";
for (Element e : element.getElementsByClass
("YOUTUBE-iframe-video"))
youtubeThumbnailImageSrc = e.attr("data-thumbnail-src");
youTubeLink = e.attr("src");
Log.e("YouTube thumbnail", youtubeThumbnailImageSrc);
Log.e("Youtube link", youTubeLink);
if (youtubeThumbnailImageSrc.isEmpty())
youtubeThumbnailImagesetVisibility = 8;
intent.putExtra("youtubeThumbnailImagesetVisibility",
youtubeThumbnailImagesetVisibility);
else
intent.putExtra("youtubeThumbnailImageSrc", youtubeThumbnailImageSrc);
intent.putExtra("youTubeLink", youTubeLink);
// String imageSrc = elements.get(0).attr("src");
// intent.putExtra("blogImage",imageSrc);
view.getContext().startActivity(intent);
);
@Override
public int getItemCount()
return items.size();
@Override
public long getItemId(int position)
return position;
@Override
public void whichFragmentAndViewModel(Fragment fragment, PostViewModel postViewModel)
this.fragment = fragment;
this.postViewModel = postViewModel;
if(position == getItemCount() -1)
postViewModel.getPosts();
notifyDataSetChanged();
public class CardViewHolder extends RecyclerView.ViewHolder
ImageView postImage;
TextView postTitle,postDescription, postDate;
private CardViewHolder(View itemView)
super(itemView);
postImage = itemView.findViewById(R.id.postImage);
postTitle = itemView.findViewById(R.id.postTitle);
postDescription = itemView.findViewById(R.id.postDescription);
postDate = itemView.findViewById(R.id.postDate);
public class CardMagazineViewHolder extends RecyclerView.ViewHolder
ImageView postImage;
TextView postTitle, postDate;
private CardMagazineViewHolder(View itemView)
super(itemView);
postImage = itemView.findViewById(R.id.postImage);
postTitle = itemView.findViewById(R.id.postTitle);
postDate = itemView.findViewById(R.id.postDate);
public class TitleViewHolder extends RecyclerView.ViewHolder
TextView postTitle;
MyImageview postImage;
private TitleViewHolder(@NonNull View itemView)
super(itemView);
postTitle = itemView.findViewById(R.id.postTitle);
postImage = itemView.findViewById(R.id.postImage);
public class GridViewHolder extends RecyclerView.ViewHolder
TextView postTitle;
MyImageview postImage;
private GridViewHolder(@NonNull View itemView)
super(itemView);
postTitle = itemView.findViewById(R.id.postTitle);
postImage = itemView.findViewById(R.id.postImage);
现在这段代码只有在我从标题或网格布局切换到其他布局并再次回到它时才起作用,我认为 onBindViewHolder 没有在第一时间检测到这个接口实现,所以挑战是如何移动这个接口的实现 insede onBindViewHolder 方法
@Override
public void whichFragmentAndViewModel(Fragment fragment, PostViewModel postViewModel)
this.fragment = fragment;
this.postViewModel = postViewModel;
if(position == getItemCount() -1)
postViewModel.getPosts();
notifyDataSetChanged();
这是我如何在片段中使用更改布局,我删除了与问题代码无关的
HomeFragment 类
private PostViewModel postViewModel;
public static final String TAG = "HomeFragment";
private RecyclerView recyclerView;
private PostAdapter adapter;
private List<Item> itemArrayList;
private boolean isScrolling = false;
private int currentItems, totalItems, scrollOutItems;
private GridLayoutManager titleLayoutManager, gridLayoutManager;
WrapContentLinearLayoutManager layoutManager;
private SharedPreferences sharedPreferences;
public ItemsDatabase itemsDatabase;
public View onCreateView(@NonNull LayoutInflater inflater,
ViewGroup container, Bundle savedInstanceState)
postViewModel = new ViewModelProvider(this).get(PostViewModel.class);
itemsDatabase = ItemsDatabase.getINSTANCE(getContext());
postViewModel.finalURL.setValue(PostsClient.getBaseUrl() + "?key=" + PostsClient.getKEY() );
postViewModel.getPosts();
View root = inflater.inflate(R.layout.fragment_home, container, false);
setHasOptionsMenu(true);
itemArrayList = new ArrayList<>();
recyclerView = root.findViewById(R.id.homeRecyclerView);
adapter = new PostAdapter(getContext(),itemArrayList);
layoutManager = new WrapContentLinearLayoutManager(getContext(),
LinearLayoutManager.VERTICAL, false);
titleLayoutManager = new GridLayoutManager(getContext(), 2);
gridLayoutManager = new GridLayoutManager(getContext(), 3);
sharedPreferences = getContext().getSharedPreferences("settings", Context.MODE_PRIVATE);
String layout = sharedPreferences.getString("recyclerViewLayout", "cardLayout");
switch (layout)
case "cardLayout":
recyclerView.setLayoutManager(layoutManager);
adapter.setViewType(0);
recyclerView.setAdapter(adapter);
break;
case "cardMagazineLayout":
recyclerView.setLayoutManager(layoutManager);
adapter.setViewType(1);
recyclerView.setAdapter(adapter);
break;
case "titleLayout":
recyclerView.setLayoutManager(titleLayoutManager);
adapter.setViewType(2);
recyclerView.setAdapter(adapter);
adapter.whichFragmentAndViewModel(this,postViewModel);
break;
case "gridLayout":
recyclerView.setLayoutManager(gridLayoutManager);
adapter.setViewType(3);
recyclerView.setAdapter(adapter);
adapter.whichFragmentAndViewModel(this,postViewModel);
recyclerView.setAdapter(adapter);
recyclerView.addOnScrollListener(new RecyclerView.OnScrollListener()
@Override
public void onScrollStateChanged(@NonNull RecyclerView recyclerView, int newState)
super.onScrollStateChanged(recyclerView, newState);
isScrolling = true;
@Override
public void onScrolled(@NonNull RecyclerView recyclerView, int dx, int dy)
super.onScrolled(recyclerView, dx, dy);
if (dy > 0)
if(layout.equals("cardLayout") || layout.equals("cardMagazineLayout"))
currentItems = layoutManager.getChildCount();
totalItems = layoutManager.getItemCount();
scrollOutItems = layoutManager.findFirstVisibleItemPosition();
else if(layout.equals("titleLayout"))
currentItems = titleLayoutManager.getChildCount();
totalItems = titleLayoutManager.getItemCount();
scrollOutItems = titleLayoutManager.findFirstCompletelyVisibleItemPosition();
else
currentItems = gridLayoutManager.getChildCount();
totalItems = gridLayoutManager.getItemCount();
scrollOutItems = gridLayoutManager.findFirstCompletelyVisibleItemPosition();
if (isScrolling && (currentItems + scrollOutItems == totalItems))
isScrolling = false;
postViewModel.getPosts();
// adapter.notifyDataSetChanged();
);
return root;
@Override
public void onCreateOptionsMenu(@NonNull Menu menu, @NonNull MenuInflater inflater)
//Empty the old menu
// if(menu.hasVisibleItems())
// menu.clear();
//
inflater.inflate(R.menu.main, menu);
super.onCreateOptionsMenu(menu, inflater);
@Override
public boolean onOptionsItemSelected(@NonNull MenuItem item)
if (item.getItemId() == R.id.change_layout)
android.app.AlertDialog.Builder builder
= new android.app.AlertDialog.Builder(getContext());
builder.setTitle(getString(R.string.choose_layout));
String[] recyclerViewLayouts = getResources().getStringArray(R.array.RecyclerViewLayouts);
SharedPreferences.Editor editor = sharedPreferences.edit();
builder.setItems(recyclerViewLayouts, (dialog, index) ->
switch (index)
case 0: // Card List Layout
adapter.setViewType(0);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "cardLayout");
editor.apply();
break;
case 1: // Cards Magazine Layout
adapter.setViewType(1);
recyclerView.setLayoutManager(layoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "cardMagazineLayout");
editor.apply();
break;
case 2: // PostTitle Layout
adapter.setViewType(2);
recyclerView.setLayoutManager(titleLayoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "titleLayout");
editor.apply();
break;
case 3: //Grid Layout
adapter.setViewType(3);
recyclerView.setLayoutManager(gridLayoutManager);
recyclerView.setAdapter(adapter);
editor.putString("recyclerViewLayout", "gridLayout");
editor.apply();
);
android.app.AlertDialog alertDialog = builder.create();
alertDialog.show();
return true;
return super.onOptionsItemSelected(item);
@Override
public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState)
super.onViewCreated(view, savedInstanceState);
WhichFragmentCalled whichFragmentCalled = adapter;
whichFragmentCalled.whichFragmentAndViewModel(this,postViewModel);
【问题讨论】:
在问题上启发我一点。您究竟想如何填充空间?我的意思是你可以调用下一页然后它会被填满。或者你为什么不将你的页面大小设置为列数的倍数呢?你能解释一下你在寻找什么样的解决方案吗? 我只是想考虑将whichFragmentAndViewModel
接口实现代码移到onBindViewHolder
内部的解决方案,这当然是在PostAdapter 内部,而不是将其直接插入其中以检测getItemCount() -1
是否意味着“还有其他帖子”然后继续通过postViewModel.getPosts();
加载帖子我希望您了解我正在寻求的解决方案的这个简单的补偿
【参考方案1】:
这更像是一个建议而不是一个答案,但是如果您要使用 ViewModel,我强烈建议您移动所有业务逻辑(几乎所有与 UI 无关的),并将其移动到您的 ViewModel 中。您可以从 android 网站了解更多关于 MVVM 架构的信息。
至于你的实际问题,如果你只显示 10 个对象,那么听起来你的数据列表只有 10 个对象 - 所以我建议验证你从改造中收到的数据列表,然后在它传递给它时验证它你的适配器。日志和/或断点将为您提供帮助。
另外,为了简单起见,我会将onCreateView()
中setHasOptionsMenu(true);
之后的所有代码移动到onViewCreated()
中,这样您就不会意外看到空视图。然后,我会将您所有的适配器/recyclerview 逻辑移动到 onResume()
中,以便在配置/状态更改时正确恢复列表/ui。
如果PostAdapter
用于所有不同的布局,则不需要您的界面。您只需要一个 Fragment 类、一个 ViewModel 和一个 RecyclerView.Adapter,因为如果我理解正确,您使用的是相同的对象列表,因此您只需要专注于更改适配器的视图/布局即可。
更改布局:
-
通过将适配器的引用设置为 null,使回收站视图中的当前可见列表无效。
recyclerView.setAdapter(null);
创建适配器的新实例,如果您的数据集保存在视图模型中,则可以将其传递给新适配器,而不是从改造中获取更多对象。
然后,将新的适配器设置回 recyclerView,并根据情况应用适当的 LayoutManager。
postViewModel.getPosts();
- 如果这是从改造中加载帖子对象,那么这是另一个潜在的错误,因为改造通常是异步的,而且看起来你没有任何条件检查来确保你的列表在通过之前准备好到适配器。您可以使用 Androids LiveData
对象轻松解决此问题。它们非常棒,非常适合您的用例。
【讨论】:
我认为存在误解,我已经知道 MVVM 并将它用于我的应用程序,PostViewModel 中的postViewModel.getPosts();
方法,我在 viewModel 本身中检查 null 和空,特别是 onResponse
改造方法像这样assert list != null; if (list != null) // Log.e(TAG, list.getNextPageToken()); token.setValue(list.getNextPageToken()); postListMutableLiveData.setValue(list);
,我也用过MutableLiveData
除非我提供了所有类,否则您将无法理解所有应用程序逻辑,这当然是不合理的,我只提供了与我的问题/问题相关的代码但是,感谢您的建议,我可以稍后受益,但在解决此问题并完成应用程序之后。
没问题 - 您是否偶然验证了您的初始列表计数?如果它只有 10 个对象并且您期望更多,那么我认为您会在初始化逻辑流程中发现问题。以上是关于如何用下一页“10 项”填充标题和网格布局的主要内容,如果未能解决你的问题,请参考以下文章