英文:
Is there any listener which callback when view is visible to user?
问题
我在ViewPager2中使用了ExoPlayer。如何在可见位置播放ExoPlayer并使用pageChangeCallback实现页面更改时播放?应该将pageChangeCallback放在哪里?是放在Fragment中还是放在适配器中?是否有任何在视图对用户可见时触发的监听器?
class VideosHolder extends RecyclerView.ViewHolder implements OnItemOnScreenListener {
SimpleExoPlayer player;
PlayerView playerView;
public VideosHolder(@NonNull final View itemView) {
super(itemView);
playerView = itemView.findViewById(R.id.videos_tab_videoView1);
}
public void setupExoPlayer(String videoUri) {
player = new SimpleExoPlayer.Builder(context).build();
playerView.setPlayer(player);
MediaItem mediaItem = MediaItem.fromUri(videoUri);
player.setMediaItem(mediaItem);
player.prepare();
player.setPlayWhenReady(false);
}
}
Note: I have translated your provided code snippet while keeping the technical terms consistent. Make sure to adjust variable names and other code elements as needed for your project.
英文:
I have exoplayer in viewpager2. How can I play exoplayer at visible position with pageChangecallback. Where should I put pageChangecallback? In fragment or adapter? Is there any listener which triggers when view is visible to user?
class videosHolder extends RecyclerView.ViewHolder implements OnItemOnScreenListener
{
SimpleExoPlayer player; PlayerView playerView;
public videosHolder(@NonNull final View itemView) {
super (itemView);
playerView = itemView.findViewById (R.id.videos_tab_videoView1);
}
public void Exoplayer(String video)
{
player = new SimpleExoPlayer.Builder(context).build();
playerView.setPlayer (player);
MediaItem mediaItem = MediaItem.fromUri(videoUri);
player.setMediaItem(mediaItem);
player.prepare();
player.setPlayWhenReady (false);
}}
答案1
得分: 0
视图在ViewPager中的可见性相当棘手,因为它一次加载两到三个片段,所有这些片段在技术上都对用户可见。一旦切换到另一个片段,除了下一个和最后一个片段,该片段也将可见。
在正常情况下,我们可以使用ViewTreeObserver
接口,它具有onGlobalLayout
接口,可以观察布局的变化。
然而,在您的情况下,您别无选择,只能使用ViewPager2.OnPageChangeCallback
回调。这也将确保视图已可见,因为在您切换到上一页时,视图已经被创建。
关于您关于将其放入片段还是适配器的问题,这是与视图相关的配置,应该放在片段中,而不是适配器中。
英文:
The view's visibility with ViewPager is quite tricky because it loads two or three fragments at once and all of them are technically
visible to the user. once you switch to another fragment this fragment will be visible in addition to the next and last fragment.
In normal cases, we can use the ViewTreeObserver
interface which has the onGlobalLayout
interface that can observe the changes in the layout.
However, in your case, you have no solution but to use the ViewPager2.OnPageChangeCallback
callback. which will also ensure that the view is already visible as it's already been created when you switched to the previous page.
About your question regarding putting it into the fragment or the adapter, this is a view-related configuration that should be put in the fragment, not the adapter.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论