How to put a RecyclerView into a Fragment? - java

I am still new for the android development. Currently, I am trying to show a RecyclerView within a Fragment. I tried to show the RecyclerView without using Fragment and it worked fine. But when it come to using Fragment, nothing is shown.
Here is the MainActivity containing the Fragment:
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//ButterKnife.bind(this);
BottomNavigationView navView = findViewById(R.id.nav_view);
navView.setOnNavigationItemSelectedListener(mOnNavigationItemSelectedListener);
mViewModel = ViewModelProviders.of(this).get(MainActivityViewModel.class);
mFragmentManager = getSupportFragmentManager();
mFragmentTransaction = mFragmentManager.beginTransaction();
mFragmentTransaction.add(R.id.fragment_container, missionListFragment).addToBackStack(null).commit();
}
And the Fragment's onCreateView method:
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_mission_list, container, false);
//ButterKnife.bind(rootview);
mRecycler = (RecyclerView) rootView.findViewById(R.id.recycler);
mFirestore = FirebaseFirestore.getInstance();
mQuery = mFirestore.collection("COLLECTION_NAME").limit(LIMIT);
if (mQuery == null) {
Log.w(TAG, "No query, not initializing RecyclerView. Created data on server.");
}
mAdapter = new RecyclerViewAdapter(mQuery, this) {
#Override
protected void onDataChanged() {
}
#Override
protected void onError(FirebaseFirestoreException e) {
// Show a snackbar on errors
Snackbar.make(getActivity().findViewById(android.R.id.content),
"Error: check logs for info.", Snackbar.LENGTH_LONG).show();
}
};
mRecycler.setLayoutManager(new LinearLayoutManager(getActivity()));
mRecycler.setAdapter(mAdapter);
return rootView;
}
With the RecyclerViewAdapter:
public class RecyclerViewAdapter extends FirestoreAdapter<RecyclerViewAdapter.ViewHolder> {
private static final int UNAVAILABLE = 0, AVAILABLE = 1;
public interface OnItemSelectedListener {
void onItemSelected(DocumentSnapshot item);
}
private OnItemSelectedListener mListener;
public RecyclerViewAdapter(Query query, OnItemSelectedListener listener) {
super(query);
mListener = listener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
return new ViewHolder(inflater.inflate(R.layout.item, parent, false));
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
holder.bind(getSnapshot(position), mListener);
}
static class ViewHolder extends RecyclerView.ViewHolder {
#BindView(R.id.view1)
TextView view1;
#BindView(R.id.view2)
TextView view2;
#BindView(R.id.view3)
TextView view3;
#BindView(R.id.view4)
TextView view4;
public ViewHolder(View itemView) {
super(itemView);
ButterKnife.bind(this, itemView);
}
public void bind(final DocumentSnapshot snapshot,
final OnItemSelectedListener listener) {
Item item = snapshot.toObject(Item.class);
Resources resources = itemView.getResources();
view1.setText(item.getfield1());
view2.setText(Integer.toString(item.getfield2()));
if(item.getfield3() == AVAILABLE)
view3.setText("Available");
else
view3.setText("Unavailable");
view4.setText(item.getfield4().toString());
// Click listener
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
if (listener != null) {
listener.onItemSelected(snapshot);
}
}
});
}
}
}
As you can notice above, I am getting data from the Firebase and displaying them as a RecyclerView. But I don't think it is the problem of empty query data, so please help.

It could be that data from firebase is not being retrieved, hence there is no content for recyclerview to display. Please check if your firebase connection is working fine and you are retrieving something from it

Related

Recycler View double items on change fragment

I have a problem with the recyclerview in my app i have 2 fragments in the first one there is the recycler view which has to find the songs present in the device and put them in line in the second for now nothing. when I switch from one fragment to another the recycler view items double each time.
CODE:
HomeActvity
public class HomeActivity extends AppCompatActivity {
BottomNavigationView bottomNavigationView;
RecyclerView recyclerView;
TextView noMusicTextView;
HomeFragment homeFragment = new HomeFragment();
ProvaFragment provaFragment = new ProvaFragment();
#SuppressLint("MissingInflatedId")
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
getSupportActionBar().hide();
noMusicTextView = findViewById(R.id.noSongs);
recyclerView = findViewById(R.id.recycler_view);
bottomNavigationView = findViewById(R.id.barra_navigazione);
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
bottomNavigationView.setOnItemSelectedListener(new NavigationBarView.OnItemSelectedListener() {
#Override
public boolean onNavigationItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.home:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, homeFragment).commit();
return true;
case R.id.prova:
getSupportFragmentManager().beginTransaction().replace(R.id.contenitore_frammenti, provaFragment).commit();
return true;
}
return false;
}
});
}
}
HomeFragment
public class HomeFragment extends Fragment {
ArrayList<AudioModel> songsList = new ArrayList<>();
RecyclerView recyclerView;
TextView noMusicTextView;
#SuppressLint("MissingInflatedId")
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_home, container, false);
recyclerView = view.findViewById(R.id.recycler_view);
noMusicTextView = view.findViewById(R.id.noSongs);
String[] projection = {
MediaStore.Audio.Media.TITLE,
MediaStore.Audio.Media.DATA,
MediaStore.Audio.Media.DURATION,
};
String selection = MediaStore.Audio.Media.IS_MUSIC + " !=0";
Cursor cursor = getActivity().getContentResolver().query(MediaStore.Audio.Media.EXTERNAL_CONTENT_URI,projection,selection,null,null);
while(cursor.moveToNext()){
AudioModel songData = new AudioModel(cursor.getString(1), cursor.getString(0),cursor.getString(2));
if(new File(songData.getPath()).exists())
songsList.add(songData);
}
if(songsList.size() == 0){
noMusicTextView.setVisibility(View.VISIBLE);
}else{
recyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
recyclerView.setAdapter(new MusicListAdapter(songsList, getContext()));
}
return view;
}
}
MusicListAdapter
public class MusicListAdapter extends RecyclerView.Adapter<MusicListAdapter.ViewHolder>{
ArrayList<AudioModel> songsList;
Context context;
public MusicListAdapter(ArrayList<AudioModel> songsList, Context context) {
this.songsList = songsList;
this.context = context;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.recycler_item,parent,false);
return new MusicListAdapter.ViewHolder(view);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
AudioModel songData = songsList.get(position);
holder.titleTextView.setText(songData.getTitle());
}
#Override
public int getItemCount() {
return songsList.size();
}
public class ViewHolder extends RecyclerView.ViewHolder{
TextView titleTextView;
ImageView iconImageView;
public ViewHolder(View itemView) {
super(itemView);
titleTextView = itemView.findViewById(R.id.music_title_text);
iconImageView = itemView.findViewById(R.id.icon_view);
}
}
}
I have tryed to use songsList.clear(); but this don't work(Sorry for my english).
When switching fragments, existing fragments aren't deleted.
Also, songsList isn't initialized; onViewCreated() is called at this time, so it seems that the transition adds the item to the songsList.
In order to solve the problem, it seems that it is necessary to do a good comparison so that the same item as the previously saved item is not added, or to not add an item every time in onViewCreated.

How to setOnClickListener in adapter using RecyclerView to display inside fragment

I cannot access the ID of the item to view it in ToastMessage, or even store it in the database (use Room DataBase)
I have tried but the message does not appear
I need the reference ID to use for database storage and complete the process for storing the shopping cart
itemAdapter.java
public class itemAdapter extends RecyclerView.Adapter<itemAdapter.ItemViewHolder> {
private Context context;
private ArrayList<Items> arrayList;
private AdapterView.OnItemClickListener listener;
public itemAdapter(Context context, ArrayList<Items> arrayList) {
this.context = context;
this.arrayList = arrayList;
}
#NonNull
#Override
public ItemViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View v = LayoutInflater.from(context).inflate(R.layout.item, parent, false);
return new ItemViewHolder(v);
}
#Override
public void onBindViewHolder(#NonNull ItemViewHolder holder, int position) {
holder.name.setText(arrayList.get(position).getItemName());
holder.desc.setText(arrayList.get(position).getItemDesc());
holder.price.setText(arrayList.get(position).getItemPrice());
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT);
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT);
}
});
}
#Override
public int getItemCount() {
return arrayList.size();
}
class ItemViewHolder extends RecyclerView.ViewHolder {
TextView name, desc, price;
ImageView remove, add;
public ItemViewHolder(#NonNull View itemView) {
super(itemView);
name = itemView.findViewById(R.id.tvName);
desc = itemView.findViewById(R.id.tvDesc);
price = itemView.findViewById(R.id.tvPrice);
remove = itemView.findViewById(R.id.btnDelete);
add = itemView.findViewById(R.id.btnAdd);
}
}
}
MealsFragment.java
public class MealsFragment extends Fragment {
public MealsFragment() {
// Required empty public constructor
}
RecyclerView recyclerView;
itemAdapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
return inflater.inflate(R.layout.fragment_meals, container, false);
}
#Override
public void onViewCreated( View view, Bundle savedInstanceState) {
ArrayList<Items> ItemsList = (ArrayList<Items>) RoomDatabaseSingleton.getInstance(getContext().getApplicationContext())
.getAppDatabase()
.getDao()
.getItems("meals");
recyclerView = view.findViewById(R.id.rvMeals);
RecyclerView.LayoutManager manager = new LinearLayoutManager(
getContext(), RecyclerView.VERTICAL, false);
recyclerView.setLayoutManager(manager);
adapter = new itemAdapter(getContext(), ItemsList);
recyclerView.setAdapter(adapter);
}
}
Try the following instead
holder.add.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemIid(),Toast.LENGTH_SHORT).show();
}
});
holder.name.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(context,arrayList.get(position).getItemPrice(),Toast.LENGTH_SHORT).show();
}
});
The static method makeText of Toast is used to create the Toast object and show() method on the Toast object is used to display the Toast

Strange behavior of OnItemClickListener inside RecyclerView inside Fragment

Need help with android app (java)
My app starts with SplashActivity. During it I`m getting json via retrofit request and after successfull response I fill my DB
SplashActivity
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_splash);
ISplashInteractor splashInteractor = new SplashInteractor();
moviePresenter = new MoviePresenter(this, splashInteractor);
moviePresenter.initDB();
}
after DB successfully loaded automatically starts MovieListActivity
public class MovieListActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_movie_list);
FragmentManager fragmentManager = getSupportFragmentManager();
FragmentTransaction transaction = fragmentManager.beginTransaction();
Fragment allMoviesFragment = new AllMoviesFragment();
String tag = "MovieList";
transaction.replace(R.id.main_container, allMoviesFragment, tag);
transaction.commit();
}
}
and at once list of movies loads inside inner fragment AllMoviesFragment(inside recyclerView). till this point everything is ok.
now I set onRecyclerViewItemClickListener - it must open another fragment inside MovieListActivity but instead of this - my app restarts from begining and I observe loading of SpalshActivity again(I put progressbar during request) and again my RecyclerView...
my RecyclerViewAdapter
public class RecyclerViewAdapter extends RecyclerView.Adapter<RecyclerViewAdapter.ViewHolder> {
private List<MovieDetails> movieList;
private OnRecyclerViewItemClickListener onRecyclerViewItemClickListener;
public RecyclerViewAdapter(List<MovieDetails> movieList) {
this.movieList = movieList;
}
public void setOnRecyclerViewItemClickListener(OnRecyclerViewItemClickListener onRecyclerViewItemClickListener){
this.onRecyclerViewItemClickListener = onRecyclerViewItemClickListener;
}
#Override
public ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View v = LayoutInflater.from(parent.getContext()).inflate(R.layout.simple_selectable_list_item, parent, false);
return new ViewHolder(v);
}
#Override
public void onBindViewHolder(ViewHolder holder, int position) {
MovieDetails movieDetails = (movieList.get(position));
holder.name.setText(movieDetails.getTitle());
holder.year.setText(String.valueOf(movieDetails.getReleaseYear()));
}
#Override
public int getItemCount() {
if (movieList == null)
return 0;
return movieList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
TextView name;
TextView year;
public ViewHolder(View itemView) {
super(itemView);
name = itemView.findViewById(R.id.movie_name);
year = itemView.findViewById(R.id.release_year);
itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(onRecyclerViewItemClickListener != null){
int position = getAdapterPosition();
if(position != RecyclerView.NO_POSITION){
onRecyclerViewItemClickListener.onRecyclerViewItemClick(position);
}
}
}
});
}
}
public interface OnRecyclerViewItemClickListener {
void onRecyclerViewItemClick(int position);
}
}
my AllMoviesFragment
public class AllMoviesFragment extends Fragment implements RecyclerViewAdapter.OnRecyclerViewItemClickListener {
private static final String CURR_MOVIE = "Current Movie";
private static final String TAG = "MSApp";
List<MovieDetails> movieList;
RecyclerView recyclerView;
public AllMoviesFragment() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
movieList = App.getAppInstance().getDatabaseInstance().getMovieDao().getAllMovies();
movieList.sort(new Comparator<MovieDetails>() {
#Override
public int compare(MovieDetails o1, MovieDetails o2) {
return o2.getReleaseYear() - o1.getReleaseYear();
}
});
View resultView = inflater.inflate(R.layout.fragment_all_movies, container, false);
recyclerView = resultView.findViewById(R.id.recycler_view);
RecyclerView.LayoutManager layoutManager = new LinearLayoutManager(getActivity());
recyclerView.setLayoutManager(layoutManager);
recyclerView.setHasFixedSize(true);
RecyclerViewAdapter adapter = new RecyclerViewAdapter(movieList);
adapter.setOnRecyclerViewItemClickListener(AllMoviesFragment.this);
recyclerView.setAdapter(adapter);
return resultView;
}
#Override
public void onRecyclerViewItemClick(int position) {
MovieDetails choosenMovie = movieList.get(position);
FragmentManager fragmentManager = getFragmentManager();
Fragment movieDetailsFragment = new MovieDetailsFragment();
Bundle args = new Bundle();
args.putParcelable(CURR_MOVIE, choosenMovie);
movieDetailsFragment.setArguments(args);
String tag = "MovieDetails";
FragmentTransaction transaction = fragmentManager.beginTransaction();
transaction.replace(R.id.main_container, movieDetailsFragment, tag);
transaction.addToBackStack(tag);
transaction.commit();
}
}
sorry for long post. I dont know how to cut it
I use App class for db access if it is important
#AkakiKapanadze
you was almost right
I didnot see the error message because it disappeared less 1 second
and class MovieDetailsFragment
after I remove binder of ButterKnife all work... I dont know WHY - I always use Butterknife inside Fragments

showing RecyclerView on fragment with data from Firebase

I'm having a problem with making a RecycleView in a fragment with data from Firebase. I expect the app to show the RecycleView after I clicked on a button to change from one fragment to the RecycleView fragment, but it does change the showed fragment but it does not show anything.
I know there are plenty of questions like this but I don't seem to find the correct solution to this problem.
I've made everything needed for a Firebase RecyclerView, and also tried to build it inside an activity instead fragment and it did work, but not with the fragment.
I've tried to initialize the adapter and recyclerview inside the onCreateView method, onActivityCreated, and onViewCreated method and none of them seem to be working.
Here's my fragment code:
private KidAdapter adapter;
private RecyclerView recyclerView;
Button button;
View view;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
view = inflater.inflate(R.layout.uangsaku_menu_fragment, container, false);
button = view.findViewById(R.id.btn_add);
button.setOnClickListener(this);
recyclerView = view.findViewById(R.id.recyclerView);
recyclerView.setHasFixedSize(true);
setUpRecyclerView();
return view;
}
#Override
public void onClick(View v) {
if(v.getId() == R.id.btn_add){
Intent intent = new Intent(getActivity(), Register.class);
startActivity(intent);
}
}
public void setUpRecyclerView(){
Query query = FirebaseDatabase.getInstance().getReference("kids");
FirebaseRecyclerOptions<kidData> options = new FirebaseRecyclerOptions.Builder<kidData>()
.setQuery(query, kidData.class)
.build();
adapter = new KidAdapter(options);
LinearLayoutManager linearLayoutManager = new LinearLayoutManager(getContext(), LinearLayoutManager.HORIZONTAL, false);
recyclerView.setLayoutManager(linearLayoutManager);
recyclerView.setAdapter(adapter);
}
#Override
public void onStart() {
super.onStart();
if (adapter != null) {
adapter.startListening();
}
}
#Override
public void onStop() {
super.onStop();
if (adapter != null) {
adapter.stopListening();
}
}
}
The adapter class
public class KidAdapter extends FirebaseRecyclerAdapter<kidData, KidAdapter.KidViewHolder> {
public KidAdapter(#NonNull FirebaseRecyclerOptions<kidData> options) {
super(options);
}
#Override
protected void onBindViewHolder(#NonNull KidViewHolder holder, int position, #NonNull kidData model) {
holder.nama.setText(model.getKidName());
holder.balance.setText(model.getKidBalance());
holder.limit.setText("Limit: "+model.getKidLimit());
holder.spending.setText("Spending xxx.xxx");
}
#NonNull
#Override
public KidViewHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View v = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.kids_card,
viewGroup, false);
return new KidViewHolder(v);
}
public class KidViewHolder extends RecyclerView.ViewHolder {
TextView nama, balance, limit, spending;
public KidViewHolder(#NonNull View itemView) {
super(itemView);
nama = itemView.findViewById(R.id.tv_nama);
balance = itemView.findViewById(R.id.tv_balance);
limit = itemView.findViewById(R.id.tv_dailylimit);
spending = itemView.findViewById(R.id.tv_dailyspending);
}
}
}
The kidData model class
public class kidData {
String kidName, kidEmail, kidDoB, kidLimit, kidBalance;
public kidData(){
}
public kidData(String kidName, String kidEmail, String kidDoB, String kidLimit, String kidBalance) {
this.kidName = kidName;
this.kidEmail = kidEmail;
this.kidDoB = kidDoB;
this.kidLimit = kidLimit;
this.kidBalance = kidBalance;
}
public String getKidName() {
return kidName;
}
public String getKidEmail() {
return kidEmail;
}
public String getKidDoB() {
return kidDoB;
}
public String getKidLimit() {
return kidLimit;
}
public String getKidBalance() {
return kidBalance;
}
}
The problem in your code is the use of the following line of code:
recyclerView.setHasFixedSize(true);
And this is because when using the latest version of Firebase-UI library, there is no need to set the size of the RecyclerView as fixed. The solution for solving this problem is to simply remove/comment the above line of code. That's it!

Mediaplayer not pausing while switching fragment

I am new to android studio. Please help. I have an app with 3 fragments, one have list of video view using recycler adapter, one have list of image view, other have same list of video view as no 1 fragment. First and last fragment are using same adapter. The problem is that while switching fragmment from first one to second video keeps playing.
//fragment code
public class funny_moments extends Fragment {
FirebaseDatabase database = FirebaseDatabase.getInstance();
DatabaseReference myRef = database.getReference("funnymomments");
ArrayList<funny_momments_row> data;
funny_momments_adapter adapter;
VideoView mVideoView;
View pos;
private RecyclerView mRecyclerView;
public funny_moments() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_funny_moments, container, false);
mRecyclerView =(RecyclerView) view.findViewById(R.id.recylerview);
mVideoView = (VideoView)view.findViewById(R.id.videoView);
data = new ArrayList<>();
myRef.addValueEventListener(new ValueEventListener() {
#Override
public void onDataChange(#NonNull DataSnapshot dataSnapshot) {
for (DataSnapshot videoSnapshot : dataSnapshot.getChildren()){
funny_momments_row video = new funny_momments_row(videoSnapshot.child("like").getValue().toString(),videoSnapshot.child("url").getValue().toString());
data.add(video);
}
adapter = new funny_momments_adapter(getActivity(),data,mCommunication);
mRecyclerView.setAdapter(adapter);
mRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
}
#Override
public void onCancelled(#NonNull DatabaseError databaseError) {
}
});
// Inflate the layout for this fragment
return view;
}
#Override
public void onPause() {
adapter.mMediaPlayer.pause();
super.onPause();
}
//adapter code
public class funny_momments_adapter extends RecyclerView.Adapter<funny_momments_adapter.funnyVideoHolder> {
private final LayoutInflater inflator;
List<funny_momments_row> data = Collections.emptyList();
communication mCommunicator;
Context mContext;
public funny_momments_adapter(Context context, List<funny_momments_row> data, communication communicator){
inflator = LayoutInflater.from(context);
this.data = data;
this.mContext = context;
mCommunicator = communicator;
}
#NonNull
#Override
public funnyVideoHolder onCreateViewHolder(#NonNull ViewGroup viewGroup, int i) {
View view = inflator.inflate(R.layout.funny_momments_row,viewGroup,false);
funnyVideoHolder funnyHolder = new funnyVideoHolder(view,mCommunicator);
return funnyHolder;
}
#Override
public void onBindViewHolder(#NonNull final funnyVideoHolder viewHolder, int i) {
funny_momments_row current = data.get(i);
VideoView f1 = viewHolder.mVideoView;
viewHolder.mVideoView.setVideoURI(Uri.parse(current.getUrl()));
viewHolder.likecount.setText(current.getLike());
viewHolder.mVideoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(final MediaPlayer mp) {
FragmentManager manager = ((AppCompatActivity)mContext).getSupportFragmentManager();
Fragment f = manager.findFragmentByTag("android:switcher:" + R.id.viewPager + ":" + 2);
mMediaPlayer = mp;
viewHolder.playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (mp.isPlaying()) {
mp.pause();
}
else {
mp.start();
}
}
});
}
});
viewHolder.playpause.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (viewHolder.mVideoView.isPlaying()) {
viewHolder.mVideoView.requestFocus();
viewHolder.mVideoView.pause();
}
else {
viewHolder.mVideoView.requestFocus();
viewHolder.mVideoView.start();
}
}
});
}
#Override
public int getItemCount() {
return data.size();
}
public class funnyVideoHolder extends RecyclerView.ViewHolder implements View.OnClickListener{
VideoView mVideoView;
ImageView likeicon;
TextView likecount;
ImageView playpause;
communication mCommunication;
public funnyVideoHolder(#NonNull View itemView,communication communication) {
super(itemView);
mVideoView = (VideoView)itemView.findViewById(R.id.videoView);
likeicon = (ImageView)itemView.findViewById(R.id.likeicon);
likecount = (TextView)itemView.findViewById(R.id.likecount);
playpause = (ImageView)itemView.findViewById(R.id.playpause);
mCommunication = communication;
}
#Override
public void onClick(View v) {
mCommunication.respond(v);
}
}
}
I want to stop playback while switching fragment.
When you fragment from one fragment to another, previous fragment's onPause() is called (giving you the opportunity to pause the video) and new fragment's onResume() function is called. If new fragment was not already created, onStart,onCreate() etc method are called before onResume() is called.
What you can do, when a fragment gets out of focus, thus called onPause(), pause your video, and when a fragment get in focus, you can resume it if it was already create.
Fragment Lifecycle (source)

Categories