Onclick on view pager in android does not work in my code
Use clicklistener inside the item of ViewPager. This is not working because Child of ViewPager is intercepting event of parent(i.e ViewPager). E.G if you are adding ImageView inside ViewPager using PagerAdapter then use click of ImageView to make it simple
onClick on ViewPager not triggered
Indeed the viewpager is interfering. But you can override the methods of the viewpager to make it do what you want. You'll need to override the ViewGroup.onInterceptTouchEvent(MotionEvent ev) method.
You could just always return false to allow the touch events to fall through. I would also recommend calling super.onInterceptTouchEvent(ev) to allow swipes to keep working.
It passes in a MotionEvent, so you could check for clicks with that if you wanted.
Hope that helps. It should at least get you started. Post back with questions or further problems.
EDIT:
Note also that the ViewPager doesn't consume clicks. Therefore you could easily set an onclicklistener on any or all of the children of the viewpager if you wanted to capture clicks and potentially save yourself a lot of work.
OnClick Listener is not triggered inside a fragment with View Pager
I solved this issue using the following chunk of code:
@Override
public void onViewCreated(View view, Bundle savedInstanceState){
view.setOnClickListener(new OnClickListener(){
public void onClick(View v){
/* Do as you please here. */
}
});
}
The reference for this answer can be viewed here: How to detect click on ImageView in ViewPager's PagerAdapter (android)?
onClick not working in viewpager android
I did it by creating a method for clicking that image and all coding was done in viewpager class. The method is as follows:
public void onClickSlideDown(View view) {
Animation slideback;
ImageView iconimage, whitebox;
TextView titletext, title_2text, descriptiontext;
titletext = (TextView)findViewById(R.id.title);
title_2text = (TextView)findViewById(R.id.title_2);
descriptiontext = (TextView)findViewById(R.id.description);
iconimage = (ImageView)findViewById(R.id.icon);
whitebox = (ImageView)findViewById(R.id.whitebox);
slideback = AnimationUtils.loadAnimation(this, R.anim.whiteboxanimback);
slideback.setAnimationListener(this);
whitebox.startAnimation(slideback);
iconimage.startAnimation(slideback);
titletext.startAnimation(slideback);
title_2text.startAnimation(slideback);
descriptiontext.startAnimation(slideback);
if (viewPager.getCurrentItem() < viewPager.getAdapter().getCount()) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
} else {
Intent i1 = new Intent(this, glass_3.class);
startActivity(i1);
}
}
viewpager not detecting onclicklistener
Okay so in your SlidingImage_Adapter
we will do some changes for your instantiateItem
method.
Try to change your instantiateItem
method into this:
@Override
public Object instantiateItem(ViewGroup view, final int position) {
//this is the inflater
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
//this is the view
final View imageLayout = inflater.inflate(R.layout.slidingimages_layout, null);
//this is the imageview in the view
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
//use glide to load images into the image views
Glide.with(context)
.load(urls[position])
.into(imageView);
//click listener of each image
imageLayout.setOnClickListener(new View.OnClickListener(){
public void onClick(View v){
//this will log the page number that was click
Log.d("position","position "+position); //should work
}
});
//do this now
ViewPager viewpager = (ViewPager) view;
viewpager.addView(imageLayout, 0);
//return the view
return imageLayout;
}
Also change the isViewFromObject
method to this:
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
Also change the destroyItem
method to this:
@Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager viewpager = (ViewPager) container;
viewpager.removeView((View) object);
}
OnClick listener on Viewpager is triggered on the wrong reference
As @MikeM. suggested in the comment
Well, there are several different ways to do this. Assuming articleShareBtn is in each individual page, probably the simplest would be to articleShareBtn.setTag(rootView) after the rootView = ... line, then change your method to private Bitmap takeScreenshot(View root) { root.setDrawingCacheEnabled(true); ... }, and inside the onClick(), you would call it like Bitmap screenshotBitmap = takeScreenshot((View) view.getTag());. Follow me? Otherwise, you could keep a Map all the page Views, and use the current index to get the right one. There's a few other ways, too, if necessary.
I got it working.
My updated Adapter code is
public class ArticleAdapter extends PagerAdapter {
public List<Articles> articlesListChild;
private LayoutInflater inflater;
Context context;
View rootView;
public ArticleAdapter(Context context) {
super();
this.context = context;
}
@Override
public int getCount() {
return articlesListChild.size();
}
@Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
@Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
@SuppressLint("ClickableViewAccessibility")
@Override
public Object instantiateItem(ViewGroup container, final int position) {
inflater = LayoutInflater.from(container.getContext());
View viewLayout = inflater.inflate(R.layout.article_single_item, null, false);
final ImageView contentIv, imageContentIv;
TextView contentHeadTv, contentBodyTv, sharingTextTv;
LinearLayout articleDetailsLl;
final LinearLayout articlesPager, articleBookmarkBtn,
articleBookmarkedBtn, articleShareBtn;
contentIv = (ImageView) viewLayout.findViewById(R.id.content_iv);
contentHeadTv = (TextView) viewLayout.findViewById(R.id.content_head_tv);
contentBodyTv = (TextView) viewLayout.findViewById(R.id.content_body_tv);
articlesPager = (LinearLayout) viewLayout.findViewById(R.id.article_pager);
articlesLayout = (LinearLayout) viewLayout.findViewById(R.id.articles_layout);
rootView = viewLayout.findViewById(R.id.post_main_cv);
articleShareBtn.setTag(rootView);
RequestOptions requestOptions = new RequestOptions();
requestOptions.placeholder(R.drawable.placeholder);
articlesLayout.setVisibility(View.VISIBLE);
Glide.with(context)
.setDefaultRequestOptions(requestOptions)
.load(articlesListChild.get(position).getArticleImage())
.into(contentIv);
toolbar.setVisibility(GONE);
articlesPager.setVisibility(GONE);
contentIv.setScaleType(ImageView.ScaleType.FIT_XY);
contentHeadTv.setText(articlesListChild.get(position).getArticleHeading().trim());
contentBodyTv.setText(articlesListChild.get(position).getArticleContent().trim());
contentSourceTv.setText(articlesListChild.get(position).getArticleSource().trim());
contentSourceTv.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Uri uri = Uri.parse(articlesListChild.get(position).getArticleSourceLink());
Intent intent = new Intent(Intent.ACTION_VIEW, uri);
intent.addFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
context.startActivity(intent);
}
});
articleShareBtn.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View view) {
Bitmap screenshotBitmap = takeScreenshot((View) view.getTag());
saveAndShareScreenshot(screenshotBitmap);
}
});
container.addView(viewLayout, 0);
return viewLayout;
}
private Bitmap takeScreenshot(View root) {
root.setDrawingCacheEnabled(true);
Bitmap screenshotBitmap = root.getDrawingCache();
return screenshotBitmap;
}
private void saveAndShareScreenshot(Bitmap screenshotBitmap) {
if (ContextCompat.checkSelfPermission(context, Manifest.permission.WRITE_EXTERNAL_STORAGE) == PackageManager.PERMISSION_GRANTED) {
// Save Screenshot
File myDir = new File(Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES), "/MyApp Screenshots");
myDir.mkdir();
String fname = "Image-" + 1 + ".jpg";
File file = new File(myDir, fname);
if (file.exists()) {
file.delete();
}
try {
file.createNewFile();
FileOutputStream out = new FileOutputStream(file);
screenshotBitmap.compress(Bitmap.CompressFormat.JPEG, 100, out);
out.flush();
out.close();
} catch (Exception e) {
e.printStackTrace();
}
MediaScannerConnection.scanFile(context, new String[]{file.toString()}, new String[]{file.getName()}, null);
// Share Screenshot
file.setReadable(true, false);
final Intent intent = new Intent(Intent.ACTION_SEND);
intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
Uri photoURI = FileProvider.getUriForFile(context, "com.xyz.abcapp.provider", file);
String shareBody = "Share"
intent.putExtra(android.content.Intent.EXTRA_SUBJECT, "Read this article");
intent.putExtra(android.content.Intent.EXTRA_TEXT, shareBody);
intent.putExtra(Intent.EXTRA_STREAM, photoURI);
intent.setType("image/*");
context.startActivity(Intent.createChooser(intent,"Share Using"));
} else {
Toast.makeText(context, "Permissions not granted", Toast.LENGTH_SHORT).show();
}
}
On Click listener is not working in View Pager
I Face this same problem,In my case it solved by set click listener in instantiateItem. You can do something like this may it can helpful
click.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
// TODO Auto-generated method stub
}
});
or
You Can try this also
click.setOnClickListener(act);
Related Topics
How to Use Device Default Theme for App
Detect If an App Is Installed from Play Store
How to Do Page Flip/Turn/Curl Effect in Android
Modifying the Android Seekbar Widget to Operate Vertically
How to Put an Image in an Alertdialog? Android
Can't Apply System Screen Brightness Programmatically in Android
Permission Denied (Missing Internet Permission): But Permission Is Given
Getting "Caused By: Java.Lang.Verifyerror:"
How to Change Screen Orientation in the Android Emulator
How to Get All Child's Data in Firebase Database
Android SQLite Database, Why Drop Table and Recreate on Upgrade
Applying Effects on Video Being Played
Receive Mms Messages in Android Kitkat
Error Type 3: Activity Class {...} Does Not Exist
Java.Lang.Illegalargumentexception: Can Only Use Lower 16 Bits for Requestcode