how to stop current fragment media player when moved to next fragment? - java

I have two Fragments with tabLayout and I am trying to stop current sound of a fragment when i want to play sound in another fragment
this is my adapter class
public class Adapter extends RecyclerView.Adapter<Adapter.holder> {
public Context context;
String data[];
int images[];
int sound[];
holder h;
int playPosition = -1;
public Adapter() {
}
//constructor
public Adapter(String[] data, int[] images, int[] sound, Context context) {
this.data = data;
this.images = images;
this.sound = sound;
this.context = context;
h = null;
playPosition = -1;
}
//class holder
public class holder extends RecyclerView.ViewHolder {
AppCompatImageView imageView;
TextView textView;
MediaPlayer mPlayer;
public holder(#NonNull View itemView) {
super(itemView);
textView = itemView.findViewById(R.id.text_view);
imageView = itemView.findViewById(R.id.img_view);
}
}
#NonNull
#Override
public holder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater inflater = LayoutInflater.from(parent.getContext());
View view = inflater.inflate(R.layout.singleview, parent, false);
return new holder(view);
}
#Override
public void onBindViewHolder(#NonNull final holder holder, final int position) {
holder.textView.setText(data[position]);
holder.imageView.setImageResource(images[position]);
holder.imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
try {
if (holder.mPlayer != null) {
holder.mPlayer.release();
holder.mPlayer = null;
}
holder.mPlayer = MediaPlayer.create(context, sound[position]);
// stops the previous sound
if (h != null && playPosition != -1 && position != playPosition) {
h.mPlayer.stop();
h.mPlayer = MediaPlayer.create(context, sound[playPosition]);
}
holder.mPlayer.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
#Override
public void onPrepared(MediaPlayer mediaPlayer) {
holder.mPlayer.start();
Toast.makeText(context, "started", Toast.LENGTH_SHORT).show();
mediaPlayer.setOnCompletionListener(new MediaPlayer.OnCompletionListener() {
#Override
public void onCompletion(MediaPlayer mediaPlayer) {
mediaPlayer.stop();
mediaPlayer.release();
holder.mPlayer = null;
Toast.makeText(context, "Finished", Toast.LENGTH_SHORT).show();
// holder.playIcon.setVisibility(View.VISIBLE);
}
});
}
});
} catch (Exception e) {
e.printStackTrace();
}
h = holder;
playPosition = position;
}
});
}
#Override
public int getItemCount() {
return data.length;
}
}
and this is my fragment
public class NatureForest extends Fragment {
RecyclerView recyclerView;
public NatureForest() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// Inflate the layout for this fragment
View view = inflater.inflate(R.layout.fragment_main, container, false);
String tab2Text[] = {"Forest forest","Forest creek","Forest leaves","Forest birds",
"Forest waterfall","Forest wind","Forest fire",
"Forest grasshopper", "Forest frogs"};
int tab2Images[] = {R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,
R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2,R.drawable.ic_rain2};
int sound[]={R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,
R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,R.raw.sounds,
R.raw.sounds};
recyclerView =view.findViewById(R.id.recycler_view);
recyclerView.setLayoutManager(new GridLayoutManager(getActivity(),3));
recyclerView.setAdapter(new Adapter(tab2Text,tab2Images,sound,getContext()));
return view;
}
}
here if a sound in one fragment is played and at the same time another sound played from 2nd fragment , the previous fragment sound is not stopped.

onPause()
: The system calls this method as the first indication that the user is leaving the fragment. This is usually where you should commit any changes that should be persisted beyond the current user session
Just override this method and pause the mediaplayer instance in that fragment

Related

How to block particular Position in Adapter class ANDROID JAVA

I have an adapter class Where i Want to show a BLOCK USER dialog on particular position.
for example if i want to block position 1 of recyclerView .
So can any one help me porgrammatically?
Given below is the Code Of adapter Please check
I want to block user profile based on Recycler View position
if someone could help me in it please;
public class TableProfileAdapter extends RecyclerView.Adapter<TableProfileAdapter.MyViewHolder> {
Context context;
Activity getActivity;
List<TableProfile> profileUser;
OnRecItemClick onRecItemClick;
private boolean isScaleAnimationDone = false;
private boolean isTimerTextViewActionUpCalled = false;
public TableProfileAdapter(List<TableProfile> profileUser, Context context) {
this.profileUser = profileUser;
this.context = context;
}
#NonNull
#Override
public MyViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(context).inflate(R.layout.profile_item, parent, false);
return new MyViewHolder(view, onRecItemClick);
}
#Override
public void onBindViewHolder(#NonNull MyViewHolder holder, int position) {
TableProfile data = profileUser.get(position);
holder.tvUserName.setText(data.getProfileName());
Bitmap image = BitmapManager.byteToBitmap(data.getProfileImage());
holder.profilePic.setImageBitmap(image);
if (context instanceof AccessProfileManagementActivity) {
context.startActivity(new Intent(context,HomeActivity.class));
} else if (context instanceof ProfileManagement) {
holder.itemView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent intent = new Intent(context, ProfileDetailsActivity.class);
TableProfile model = profileUser.get(holder.getAdapterPosition());
intent.putExtra("DATA", model);
context.startActivity(intent);
notifyDataSetChanged();
((Activity) context).finish();
}
});
}
}
#Override
public int getItemCount() {
return profileUser.size();
}
public class MyViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
CircleImageView profilePic;
TextView tvUserName, birthday;
OnRecItemClick onRecItemClick;
RelativeLayout relativeLayout;
public MyViewHolder(#NonNull View itemView, OnRecItemClick onRecItemClick) {
super(itemView);
profilePic = itemView.findViewById(R.id.profileImage);
tvUserName = itemView.findViewById(R.id.userName);
relativeLayout = itemView.findViewById(R.id.relTop);
this.onRecItemClick = onRecItemClick;
itemView.setOnClickListener(this);
}
#Override
public void onClick(View view) {
onRecItemClick.onItemClick(getAdapterPosition());
}
}
public interface OnRecItemClick {
void onItemClick(int position);
}
}

How to solve position problem in adapter? Using firebase as the backend

I'm creating an app with firebase as a backend. I'm using same adapter for different activity, now it is working good but positions were mismatched for example: The output of position 0 shows in position 1 and for position 1 shows in position 2 and so on.. How to solve this problem, The problem with the positions of the output.
Adapter:
public class FrontlistAdapter extends FirebaseRecyclerAdapter<Gamedata, FrontlistAdapter.ViewHolder> {
private static final String TAG = "GameAdapter";
Context mContext;
int positions;
public FrontlistAdapter(#NonNull FirebaseRecyclerOptions<Gamedata> options, Context context) {
super(options);
mContext = context;
}
#Override
protected void onBindViewHolder(#NonNull ViewHolder holder, int position, #NonNull Gamedata model) {
holder.name.setText(model.getName());
holder.address.setText(model.getAddress());
//Picasso.get().load(model.getFrontcover()).into(holder.Frontcover);
Glide.with(mContext).load(model.getFrontcover()).into(holder.Frontcover);
positions = position; //<-- here I'm having positions but output shows different for each positions
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(parent.getContext());
View v = layoutInflater.inflate(R.layout.gamerow,parent,false);
ViewHolder viewHolder = new ViewHolder(v);
return viewHolder;
}
public class ViewHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
ImageView Frontcover;
TextView name;
TextView address;
View v;
public ViewHolder(#NonNull View itemView) {
super(itemView);
Frontcover = (ImageView)itemView.findViewById(R.id.frontcover);
name = (TextView)itemView.findViewById(R.id.frontname);
address=(TextView)itemView.findViewById(R.id.frontaddress);
v = itemView;
itemView.setClickable(true);
itemView.setOnClickListener((View.OnClickListener) this);
}
#Override
public void onClick(View v) {
String className = mContext.getClass().getSimpleName();
Intent intent = null;
switch (className) {
case "GameActivity":
intent = new Intent(mContext, Center_details.class);
intent.putExtra("User", getRef(positions).getKey());
break;
case "KidsActivity":
intent = new Intent(mContext,AllCenterDetails.class);
intent.putExtra("Kids",getRef(positions).getKey());
break;
}
mContext.startActivity(intent);
}
}
}
first what you have to do is create the interface like this
public interface ClickListner {
void onClick(View view, int position);
}
then in your activity create object of the interface like this and pass to the adapter along with your other data
ClickListner listener = ClickListner();
FrontlistAdapter customAdapter = new
FrontlistAdapter(AcceptedOrdersActivity.this,listener);
riderView.setAdapter(customAdapter);
copy this outside onCreate and intent in this
private ClickListner ClickListner() {
ClickListner listener = new ClickListner() {
#Override
public void onClick(View view, int position) {
int tag = (int) view.getTag();
if(tag == 0)
{
//Intent here
}
}
};
return listener;
}
now your adapter should be this one
public class FrontlistAdapter extends
RecyclerView.Adapter<FrontlistAdapter .DataObjectHolder>{
ClickListner listenr;
Context context;
public FrontlistAdapter (Context context,ClickListner listenr) {
this.context = context;
this.listenr = listenr;
}
public static class DataObjectHolder extends RecyclerView.ViewHolder {
Context context;
public DataObjectHolder(View itemView,ClickListner listenr) {
super(itemView);
this.listenr = listenr;
Frontcover = (ImageView)itemView.findViewById(R.id.frontcover);
name = (TextView)itemView.findViewById(R.id.frontname);
address=(TextView)itemView.findViewById(R.id.frontaddress);
v = itemView;
setOnClickListeners();
}
private void setOnClickListeners() {
`v.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
v.setTag(0);
listenr.onClick(v, getAdapterPosition());
}
});
}
}
#NonNull
#Override
public FrontlistAdapter.DataObjectHolder onCreateViewHolder(#NonNull ViewGroup parent,
int viewType) {
View view = LayoutInflater.from(parent.getContext())
.inflate(R.layout.cell_orderdetail_list, parent, false);
FrontlistAdapter.DataObjectHolder dataObjectHolder = new
FrontlistAdapter.DataObjectHolder(view,listenr);
return dataObjectHolder;
}
#Override
public void onBindViewHolder(#NonNull FrontlistAdapter.DataObjectHolder holder, int
position) {
}
#Override
public int getItemCount() {
return options.size;
}
}
positions = position;
This is your problem. You're setting one global position for everything in the adapter.
Everywhere you are currently using position, you should instead be calling getBindingAdapterPosition() on the ViewHolder.

Exoplayer not stopping after app closes in PagerAdapter

I have problem with Exoplayer to stopping after the app is closed down, or the fragment is changed from the BottomNavigationView, I get the data from my API that is cast to a Recyclerview/Adapter that handle the data, then the data with the images and video is gettting showed with a PagerAdapter.
I also tried in the fragment to set a onDestroy, but not working.
FeedAdapter.java
public class FeedAdapter extends RecyclerView.Adapter<FeedAdapter.ViewHolder> {
private final List<FeedData> feedList;
private Activity context;
private View.OnClickListener onClickListener;
private SimpleExoPlayer videoPlayer;
REST apiService =
RestClient.getClient().create(REST.class);
public FeedAdapter(Activity context, List<FeedData> feedList) {
this.context = context;
this.feedList = feedList;
this.onClickListener = onClickListener;
}
public List<FeedData> getFeedData(){
return feedList;
}
#NonNull
#Override
public ViewHolder onCreateViewHolder(#NonNull ViewGroup parent, int viewType) {
View view = LayoutInflater.from(parent.getContext()).inflate(R.layout.list_item_feed_photo, parent, false);
return new ViewHolder(view);
}
#Override
public void onBindViewHolder(#NonNull ViewHolder holder, int position) {
holder.mBinding.setFeed(feedList.get(position));
Boolean isLiked = holder.mBinding.getFeed().getIsLiked();
Boolean isSaved = holder.mBinding.getFeed().getIsSaved();
String username = holder.mBinding.getFeed().getUsername();
if (holder.mBinding.getFeed().getAvatar().length() > 0) {
Glide.with(context).load(holder.mBinding.getFeed().getAvatar())
.diskCacheStrategy(DiskCacheStrategy.NONE)
.into(holder.mBinding.userAvatar);
}
holder.mBinding.username.setText(username);
holder.mBinding.description.setHashtagModeColor(ContextCompat.getColor(context, R.color.fitnessm8_green));
holder.mBinding.description.addAutoLinkMode(AutoLinkMode.MODE_HASHTAG, AutoLinkMode.MODE_MENTION);
holder.mBinding.description.setAutoLinkText(holder.mBinding.getFeed().getDescription());
holder.mBinding.likecount.setText(holder.mBinding.getFeed().getLikes().toString());
holder.mBinding.likecounttext.setText(context.getResources().getString(R.string.likes));
holder.mBinding.commentcount.setText(holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
holder.mBinding.viewMoreComment.setText(context.getResources().getString(R.string.view) + " " + holder.mBinding.getFeed().getComments().size() + " " + context.getResources().getString(R.string.comments));
holder.mBinding.viewMoreComment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
if (isLiked) {
holder.mBinding.like.setLiked(true);
} else {
holder.mBinding.like.setLiked(false);
}
if (isSaved) {
holder.mBinding.fav.setLiked(true);
} else {
holder.mBinding.fav.setLiked(false);
}
if (holder.mBinding.getFeed().getType().equals("image")) {
if (holder.mBinding.getFeed().getMediaSet().size() > 1) {
holder.mBinding.image.setVisibility(View.GONE);
MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
holder.mBinding.viewpagerId.setAdapter(pagerAdapter);
ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
} else {
holder.mBinding.viewpagerId.setVisibility(View.GONE);
Glide.with(context).load(holder.mBinding.getFeed().getMediaSet().get(0).getFile())
.placeholder(R.drawable.image_placeholder)
.error(R.drawable.image_placeholder)
.into(holder.mBinding.image);
}
}
if (holder.mBinding.getFeed().getType().equals("video")) {
holder.mBinding.image.setVisibility(View.GONE);
MultiMediaAdapter pagerAdapter = new MultiMediaAdapter(context, holder.mBinding.getFeed().getMediaSet());
holder.mBinding.viewpagerId.setAdapter(pagerAdapter);
ScrollingPagerIndicator pagerIndicator = holder.mBinding.indicator;
pagerIndicator.attachToPager(holder.mBinding.viewpagerId);
}
holder.mBinding.clickUser.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Intent i = new Intent(context, UserProfileActivity.class);
i.putExtra("profileUserID", holder.mBinding.getFeed().getUserId());
view.getContext().startActivity(i);
}
});
}
#Override
public int getItemCount() {
return feedList.size();
}
class ViewHolder extends RecyclerView.ViewHolder {
ListItemFeedPhotoBinding mBinding;
public ViewHolder(View itemView) {
super(itemView);
mBinding = DataBindingUtil.bind(itemView);
}
}
#Override
public int getItemViewType(int position) {
return super.getItemViewType(position);
}
public interface ClickListener {
void onClick(View view, int position);
void onLongClick(View view, int position);
}
}
MultiMediaAdapter.java
public class MultiMediaAdapter extends PagerAdapter {
private PlayerView simpleExoPlayerView;
private SimpleExoPlayer player;
private ImageView image;
Context context;
List<FeedMediaSet> Media_list;
public MultiMediaAdapter(Context context, List<FeedMediaSet> Media_list) {
this.context = context;
this.Media_list = Media_list;
}
#Override
public int getCount() {
return Media_list.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
FeedMediaSet mediaObj = Media_list.get(position);
if (mediaObj.getType().equals("image")) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item_media_photo,container,false);
image = view.findViewById(R.id.image);
Glide.with(context).load(mediaObj.getFile())
.placeholder(R.drawable.image_placeholder)
.error(R.drawable.image_placeholder)
.into(image);
container.addView(view);
return view;
} else if (mediaObj.getType().equals("video")) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.list_item_media_video,container,false);
simpleExoPlayerView = view.findViewById(R.id.playerView);
image = view.findViewById(R.id.image);
image.setVisibility(View.GONE);
initializePlayer(mediaObj.getFile(), mediaObj.getExtra());
container.addView(view);
return view;
}
return null;
}
private void initializePlayer(String uri, String extra) {
player = ExoPlayerFactory.newSimpleInstance(context);
try {
Uri mp4VideoExtraUri = Uri.parse(uri);
InputStream inputStream = context.getContentResolver().openInputStream(mp4VideoExtraUri);
Drawable yourDrawable = Drawable.createFromStream(inputStream, extra);
simpleExoPlayerView.setDefaultArtwork(yourDrawable);
} catch (FileNotFoundException e) {
Drawable yourDrawable = context.getResources().getDrawable(R.drawable.image_attach);
simpleExoPlayerView.setDefaultArtwork(yourDrawable);
}
DataSource.Factory mediaDataSourceFactory = new DefaultDataSourceFactory(context, Util.getUserAgent(context, context.getResources().getString(R.string.app_name)));
MediaSource videoSource = new ProgressiveMediaSource.Factory(mediaDataSourceFactory)
.createMediaSource(Uri.parse(uri));
player.setPlayWhenReady(false);
player.prepare(videoSource);
if (simpleExoPlayerView != null) simpleExoPlayerView.setPlayer(player);
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
releasePlayer();
}
private void releasePlayer() {
if (player != null) {
player.release();
player = null;
simpleExoPlayerView.setPlayer(null);
}
}
}

Problem shared element transition does not work between viewpage and recycleview when I select an other page in view page

I have fragment adapter for recycle view and as we know for do shared element we have to settransitionName for image view in xml but in recyle view we set transition name programmatically for each one and in view page I set transition name in view page adapter for imageview that i want to apply shared element transition...
by the way, shared element work very well (when I click in image in recycle view the shared element work with image in view pager) but the main problem that why I post this question is when select an other image in view page,shared element does not work and it shared element transition with old image in recycle view (sorry about any lexial mistakes because english is not my original language).
Recycleview adapter:
public class GridAdapter extends RecyclerView.Adapter<GridAdapter.GridViewHolder> {
int lastAnimatedPosition=-1;
Context context;
String[] data;
AssetManager as;
FragmentManager fragmentManager;
public GridAdapter(Context context,String[] data,AssetManager as, FragmentManager fragmentManager) {
this.context=context;
this.data=data;
this.as=as;
this.fragmentManager=fragmentManager;
}
#Override
public GridAdapter.GridViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
View view= LayoutInflater.from(parent.getContext()).inflate(R.layout.chantion_gridview,parent,false);
GridViewHolder Holder=new GridViewHolder(view);
return Holder;
}
private void runEnterAnimation(View view, int position) {
if (position >= data.length - 1) {
return;
}
if (position > lastAnimatedPosition) {
lastAnimatedPosition = position;
view.setTranslationY(GlobalFunctions.getScreenHeight(view.getContext()));
view.animate()
.translationY(0)
.setInterpolator(new DecelerateInterpolator(3.f))
.setDuration(700)
.start();
}
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#Override
public void onBindViewHolder(final GridAdapter.GridViewHolder holder, final int position) {
//runEnterAnimation(holder.itemView, position);
InputStream inputStream=null;
try{
inputStream=as.open("imagesTroll/"+position+".jpg");
}catch (IOException io){
}
int width = 200;
int height = 200;
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
holder.imageTroll.setLayoutParams(parms);
holder.imageTroll.setImageBitmap(BitmapFactory.decodeStream(inputStream));
holder.imageTroll.setTransitionName("transition"+position);
holder.imageTroll.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Bundle bundle=new Bundle();
bundle.putStringArray("images",data);
bundle.putInt("position",position);
Fragment fragment=new FragmentViewPager();
//setUp shared Element
Transition transition=TransitionInflater.from(context)
.inflateTransition(R.transition.mova);
fragment.setSharedElementEnterTransition(transition);
fragment.setSharedElementReturnTransition(transition);
fragment.setArguments(bundle);
fragmentManager.beginTransaction()
.replace(R.id.content_frame,fragment)
.addSharedElement(holder.imageTroll, ViewCompat.getTransitionName(holder.imageTroll))
.addToBackStack(null)
.commit();
}
});
}
#Override
public int getItemCount() {
return data.length;
}
class GridViewHolder extends RecyclerView.ViewHolder{
ImageButton imageTroll;
public GridViewHolder(View itemView) {
super(itemView);
imageTroll=itemView.findViewById(R.id.imageView);
}
}
}
viewpager adapter:
public class ViewPagerAdapter extends PagerAdapter {
String[] images;
int position;
Context context;
LayoutInflater layoutInflater;
ViewPagerAdapter(Context context,String[] images,int position){
this.context=context;
this.images=images;
this.position=position;
}
#Override
public int getCount() {
return images.length;
}
public static int getScreenWidth() {
return Resources.getSystem().getDisplayMetrics().widthPixels;
}
public static int getScreenHeight() {
return Resources.getSystem().getDisplayMetrics().heightPixels;
}
#RequiresApi(api = Build.VERSION_CODES.LOLLIPOP)
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup container, int position) {
layoutInflater=(LayoutInflater) context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view=layoutInflater.inflate(R.layout.chantion_view_pager,container,false);
AssetManager as=context.getAssets();
ImageView imagePost=view.findViewById(R.id.imagePost);
imagePost.setTransitionName("transition"+position);
int width = getScreenWidth();
int height = (int)(getScreenHeight()-getScreenHeight()*0.5);
LinearLayout.LayoutParams parms = new LinearLayout.LayoutParams(width,height);
imagePost.setLayoutParams(parms);
InputStream inputStream=null;
try{
inputStream=as.open("imagesTroll/"+position+".jpg");
}catch (IOException io){
}
imagePost.setImageBitmap(BitmapFactory.decodeStream(inputStream));
AdView adView = new AdView(context);
AdSize adSize=new AdSize(getScreenWidth(),100);
adView.setAdSize(adSize);
adView.setAdUnitId("ca-app-pub-3940256099942544/6300978111");
AdView mAdView = view.findViewById(R.id.adView);
AdRequest adRequest = new AdRequest.Builder().build();
mAdView.loadAd(adRequest);
container.addView(view);
return view;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((LinearLayout)object);
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object o) {
return (view==(LinearLayout)o);
}
}
I hope that any engineer helps me because this problem stops my processing.

Open different activities by clicking on different cards in CardView ,Recyclerview Fragment in Android studio

I have created a RecyclerView and added cards in fragment.I want to open different activities by clicking on different cards in CardView.But I am only able to open the same activity for all the cards.I searched different answers in StackOverFlow.But I couldn't.
could you tell me how to solve this issue...? If you can give full code,I'm happy.
Here are my codes...
PDFFragment.java
public class PDFFragment extends Fragment {
View v;
List<Pdf> listBook;
public View onCreateView(#NonNull LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
v= inflater.inflate(R.layout.fragment_pdf,container,false);
listBook = new ArrayList<>();
listBook.add(new Pdf("1-pdf name",R.drawable.pdf1image));
listBook.add(new Pdf("2-pdf name",R.drawable.pdf2image));
listBook.add(new Pdf("3-pdf name",R.drawable.pdf3image));
listBook.add(new Pdf("4-pdf name",R.drawable.pdf4image);
listBook.add(new Pdf("5-pdf name",R.drawable.pdf5image));
listBook.add(new Pdf("6-pdf name",R.drawable.pdf6image));
listBook.add(new Pdf("7-pdf name",R.drawable.pdf7image));
RecyclerView myTV= (RecyclerView) v.findViewById(R.id.recyclerview_id);
RecyclerViewAdapterPDF myAdapter = new RecyclerViewAdapterPDF(getActivity(),listBook);
//Part 1 -Start Changing number of columns
myTV.setLayoutManager(new GridLayoutManager(getActivity(),calculateNoOfColumns(getActivity())));
//Part 1 -End Changing number of columns
myTV.setAdapter(myAdapter);
return v;
}
//Part 2 -Start Changing number of columns
public int calculateNoOfColumns(Context context) {
DisplayMetrics displayMetrics = context.getResources().getDisplayMetrics();
float dpWidth = displayMetrics.widthPixels / displayMetrics.density;
int noOfColumns = (int) (dpWidth / 120);
return noOfColumns;
}
//Part 2 -End Changing number of columns
}
RecyclerViewAdapterPDF.java
public class RecyclerViewAdapterPDF extends RecyclerView.Adapter<RecyclerViewAdapterPDF.MyViewHolder> {
private Context mContext;
private List<Pdf> mData;
public RecyclerViewAdapterPDF(Context mContext, List<Pdf> mData) {
this.mContext = mContext;
this.mData = mData;
}
#Override
public MyViewHolder onCreateViewHolder( ViewGroup parent, int viewType) {
View view;
LayoutInflater mInflater = LayoutInflater.from(mContext);
view = mInflater.inflate(R.layout.cardview_item_pdf,parent,false);
return new MyViewHolder(view);
}
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
holder.tv_book_title.setText(mData.get(position).getTitle());
holder.img_book_thumbnail.setImageResource(mData.get(position).getPhoto());
}
#Override
public int getItemCount() {
return mData.size();
}
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_book_title;
ImageView img_book_thumbnail;
public MyViewHolder(View itemView) {
super(itemView);
tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id);
img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_image_id);
}
}
}
ViewPagerAdapter.java
public class ViewPagerAdapter extends FragmentPagerAdapter {
private final List<Fragment> fragmentList = new ArrayList<>();
private final List<String> FragmentListTitles = new ArrayList<>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return fragmentList.get(position);
}
#Override
public int getCount() {
return FragmentListTitles.size();
}
#Nullable
#Override
public CharSequence getPageTitle(int position) {
return FragmentListTitles.get(position);
}
public void AddFragment(Fragment fragment,String Title){
fragmentList.add(fragment);
FragmentListTitles.add(Title);
}
}
You need a reference to your card on the view holder:
public static class MyViewHolder extends RecyclerView.ViewHolder{
TextView tv_book_title;
ImageView img_book_thumbnail;
CardView cardview;
public MyViewHolder(View itemView) {
super(itemView);
tv_book_title = (TextView) itemView.findViewById(R.id.book_title_id);
img_book_thumbnail = (ImageView) itemView.findViewById(R.id.book_image_id);
cardview = itemView.findViewById(R.id.yourCardId);
}
}
And on the onBindViewHolder() you set a click listener responsible for opening the activity:
#Override
public void onBindViewHolder( MyViewHolder holder, int position) {
holder.tv_book_title.setText(mData.get(position).getTitle());
holder.img_book_thumbnail.setImageResource(mData.get(position).getPhoto());
holder.cardView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
Intent intent;
switch (position) {
case 0:
intent = new Intent(mContext, pdfone.class);
mContext.startActivity(intent);
break;
case 1:
intent = new Intent(mContext, pdftwo.class);
mContext.startActivity(intent);
break;
...
//do the same for every card possible
}
}
}
Use reflection like this
So in your case, something like:
String activityToStart = "com.pkg.pdf"+position;
try {
Class<?> c = Class.forName(activityToStart);
Intent intent = new Intent(this, c);
startActivity(intent);
} catch (ClassNotFoundException e) {
// print exception
}
Put it in adapter when page is to be changed.

Categories