I am newer in developing android app , can anybody tell me how is it possible to add an onClick listener to a drawable image? This is the code for putting the drawable images in the swapping mode but I want the user be able to go to another page by clicking on each of the drawable images. how can I add the onClick method to my code?
public class ViewAdapter extends PagerAdapter {
Context context;
private int[] GalImages = new int[] {
R.drawable.image_1,
R.drawable.image_2,
R.drawable.image_3,
R.drawable.image_4
};
ViewAdapter(Context context){
this.context=context;
}
#Override
public int getCount() {
return GalImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
Add an onClickListener to the ImageView displaying the drawable:
#Override
public Object instantiateItem(ViewGroup container, int position) {
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(GalImages[position]);
((ViewPager) container).addView(imageView, 0);
imageView.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// do something
}
});
return imageView;
}
Related
Is there a way to prevent a user swiping to the left in PagerAdapter?
When the user first enter the app they can't swipe to the left because there isn't anything there. So what if everytime you swiped to the right the left image gets destroyed and there will be nothing there like when you ran the app at first.
#Override
public Object instantiateItem(ViewGroup container, int position)
{
Context context = MainActivity.this;
//
Integer highest_img = mImages.length - 1;
Integer randomInt = getRanValue(highest_img);
//
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[randomInt]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
((ViewPager) container).removeView((ImageView) object);
}
I found a better solution for my problem.
I used the onFling() method with MotionEvent and when somebody swipe i'll just run an animation with an image replace.
i want to resizing imageview, but my code doesn't works. here's the code:
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.kuhpps,
R.drawable.kuhpps,
R.drawable.kuhpps
};
part of error code:
#Override
public Object instantiateItem(ViewGroup container, int position){
Context context = MainActivity.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.getLayoutParams().height = 30;
imageView.getLayoutParams().width = 30;
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
You need to set the Layout Params with the height and wight . You are updating the LayoutParams instance from getLayoutParams , but that won't change the view.
Do like this to change the ImageView Layout size.
ViewGroup.LayoutParams layoutParams = new ViewGroup.LayoutParams(300,300);
imageView.setLayoutParams(layoutParams);
In the viewpager's adapter:
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = ActivityGallery.this;
ImageView imageView = new ImageView(context);
imageView.setLayoutParams(new ViewGroup.LayoutParams(mScreenWidth, ViewGroup.LayoutParams.WRAP_CONTENT));
imageView.setAdjustViewBounds(true);
imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
Drawable drawable = Drawable.createFromPath(Environment.getExternalStorageDirectory() + "/Android/data/" + getPackageName() +
"/"+....+".jpg");
if(drawable != null)
imageView.setImageDrawable(drawable);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
mScreenWidth is the current screen width fetched earlier.
I want to create a ViewPager, but when I execute the application in my phone, it shows me a blank activity and then the following error message:
The application testViewPager (process com.example.testviewpager) has stopped unexpectedly. Please try again.
How can I go about fixing this problem?
Main.xml:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android" android:layout_width="match_parent" android:layout_height="match_parent">
<com.example.testviewpager.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC">
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.testviewpager.PagerContainer>
</RelativeLayout>
PagerActivity.java:
public class PagerActivity extends Activity {
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
//Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
//A little space between pages
pager.setPageMargin(15);
//If hardware acceleration is enabled, you should also remove
// clipping on the pager for its children.
pager.setClipChildren(false);
}
//Nothing special about this adapter, just throwing up colored views for demo
private class MyPagerAdapter extends PagerAdapter {
#Override
public Object instantiateItem(ViewGroup container, int position) {
TextView view = new TextView(PagerActivity.this);
view.setText("Item "+position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50, position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View)object);
}
#Override
public int getCount() {
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == object);
}
}
}
PagerContainer.java:
public class PagerContainer extends FrameLayout implements ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y - mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
#Override
public void onPageSelected(int position) { }
#Override
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
MainActivity.java:
public class MainActivity extends Activity
{
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
// Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
// A little space between pages
pager.setPageMargin(15);
}
// Nothing special about this adapter, just throwing up colored views for
// demo
private class MyPagerAdapter extends PagerAdapter
{
#Override
public Object instantiateItem(ViewGroup container, int position)
{
TextView view = new TextView(MainActivity.this);
view.setText("Item " + position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50,
position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);
}
#Override
public int getCount()
{
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return (view == object);
}
}
}
There is an image shown below for what I am looking for. Currently I am using view pager & circle indicator. In view page it is showing only a single image.
I want in one viewpager three images as shown in pic. When I slide that page, again three different images loaded form server with text below. How to do this? Any idea regarding this or any other way to achieve this?
My code is shown below.
I add some xml layout here: homespizzaview.xml
<LinearLayout
android:id="#+id/linearLayoutbutton"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="10dip" >
<android.support.v4.view.ViewPager
android:id="#+id/pagerMenu"
android:layout_width="0dip"
android:layout_height="100dip"
android:layout_weight="1"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip">
</android.support.v4.view.ViewPager>
</LinearLayout>
<RelativeLayout
android:id="#+id/relativeLayoutDot1"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginTop="5dip">
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicatorMenu"
android:layout_width="fill_parent"
android:layout_height="25dip"
android:layout_marginLeft="10dip"
android:layout_marginRight="10dip"
android:padding="10dip" />
</RelativeLayout>
HomeView .java
public class HomeView extends Activity {
adaptermenu = new MenuPagerAdapter();
pagerMenu = (ViewPager)findViewById(R.id.pagerMenu);
pagerMenu.setAdapter(adaptermenu);
pagerMenu.setCurrentItem(0);
pagerMenu.setOffscreenPageLimit(adapter.getCount());
pagerMenu.getAdapter().notifyDataSetChanged();
pagerMenu.setPageMargin(15);
indicator = (CirclePageIndicator)findViewById(R.id.indicatorMenu);
indicator.setViewPager(pagerMenu);
final float density1 = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density1);
indicator.setPageColor(0xFF000000);
indicator.setFillColor(0xFF888888);
indicator.setStrokeWidth(2 * density1);
//We set this on the indicator, NOT the pager
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// Toast.makeText(HomeSpizzaView.this, "Changed to page " + position, Toast.LENGTH_SHORT).show();
pagerMenu.setCurrentItem(position, false);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
indicator.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
pagerMenu.setCurrentItem(0);
Log.i("", "getCurrentItem"+ mPager.getCurrentItem());
pagerMenu.getAdapter().notifyDataSetChanged();
}
});
}
}
MenuPagerAdapter.java
public class MenuPagerAdapter extends PagerAdapter {
public int getCount() {
return 3;
}
public Object instantiateItem(View collection, int position) {
ImageView image = new ImageView(collection.getContext());
image.setPadding(20, 0, 20, 0);
int resId = 0;
switch (position) {
case 0:
resId = R.drawable.promotion1;
break;
case 1:
resId = R.drawable.promotion2;
break;
case 2:
resId = R.drawable.promotion3;
break;
}
image.setImageResource(resId);
((ViewPager) collection).addView(image, 0);
return image;
}
#Override
public void destroyItem(View arg0, int arg1, Object arg2) {
((ViewPager) arg0).removeView((View) arg2);
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == ((View) arg1);
}
#Override
public Parcelable saveState() {
return null;
}
}
here is update code which is showing single image view with below textview. i am looking for dynamic image & text.. means In 1 view pager 3 images with 3 text.. currently its showing 1 image view with below text.. I am looking for 3 images in single viewpager.. if i add linear layout it shows 3 image. but i add relative layout its showing single images.. ANY IDEA WHAT I MADE MISTIKE.
public Object instantiateItem(View collection, int position) {
RelativeLayout lLayout;
RelativeLayout.LayoutParams relativeLayout;
lLayout = new RelativeLayout (collection.getContext());
relativeLayout = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.FILL_PARENT, RelativeLayout.LayoutParams.FILL_PARENT);
for (int i = 0; i < 3; i++) {
image = new ImageView(collection.getContext());
image.setPadding(20, 0, 20, 0);
image.setId(1);
int res = 0;
switch (0) {
case 0:
res = R.drawable.menu_antipasti;
break;
case 1:
res = R.drawable.menu_combos;
break;
case 2:
res = R.drawable.menu_drinks;
break;
}
image.setImageResource(res);
lLayout.addView(image);
textview = new TextView(collection.getContext());
textview.setTextColor(Color.BLACK);
textview.setId(2);
textview.setText("pizza");
textview.setPadding(60, 0, 20, 0);
relativeLayout.addRule(RelativeLayout.BELOW, image.getId());
lLayout.addView(textview, relativeLayout);
}
((ViewPager) collection).addView(lLayout, 0);
return lLayout;
}
Now you're returning ImageView from instantiateItem method. If you want to have 3 images on 1 page you need to create layout, place 3 images on it and return it. E.g:
public Object instantiateItem(View collection, int position) {
LinearLayour images = new LinearLayout(collection.getContext());
for (int i = 0; i < 3; i++) {
ImageView image = new ImageView(collection.getContext());
image.setPadding(20, 0, 20, 0);
images.addView(image);
int res = someResource depending on i and position.
image.setImageResource(res);
}
((ViewPager) collection).addView(images, 0);
return images;
}
I am trying to show horizontal scroll view with images to scroll in two directions.Previously for this i used Gallery View but galleryview is deprected ,i am using horizontal scroll view instead of gallery view but horizontal scroll view is different with gallery view.
Now i have to do two implementation
1) Scrolling in two directions continuously.
2) Center lock feature as same as gallery.
My screen looks like
you can use viewpager,
try this code and modify it as your need .
note : this not my code already found it on the net belong to:
( Dave Smith,#devunwired Date: 8/17/12 PagerActivity).
MainActivity:
public class MainActivity extends Activity{
PagerContainer mContainer;
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mContainer = (PagerContainer) findViewById(R.id.pager_container);
ViewPager pager = mContainer.getViewPager();
PagerAdapter adapter = new MyPagerAdapter();
pager.setAdapter(adapter);
// Necessary or the pager will only have one extra page to show
// make this at least however many pages you can see
pager.setOffscreenPageLimit(adapter.getCount());
// A little space between pages
pager.setPageMargin(15);}
// Nothing special about this adapter, just throwing up colored views for
// demo
private class MyPagerAdapter extends PagerAdapter{
#Override
public Object instantiateItem(ViewGroup container, int position){
TextView view = new TextView(MainActivity.this);
view.setText("Item " + position);
view.setGravity(Gravity.CENTER);
view.setBackgroundColor(Color.argb(255, position * 50,
position * 10, position * 50));
container.addView(view);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);}
#Override
public int getCount(){
return 5;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return (view == object);
}}}
PagerContainer:
public class PagerContainer extends FrameLayout implements
ViewPager.OnPageChangeListener {
private ViewPager mPager;
boolean mNeedsRedraw = false;
public PagerContainer(Context context) {
super(context);
init();
}
public PagerContainer(Context context, AttributeSet attrs) {
super(context, attrs);
init();
}
public PagerContainer(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
init();
}
private void init() {
setClipChildren(false);
}
#Override
protected void onFinishInflate() {
try {
mPager = (ViewPager) getChildAt(0);
mPager.setOnPageChangeListener(this);
} catch (Exception e) {
throw new IllegalStateException("The root child of PagerContainer must be a
ViewPager");
}
}
public ViewPager getViewPager() {
return mPager;
}
private Point mCenter = new Point();
private Point mInitialTouch = new Point();
#Override
protected void onSizeChanged(int w, int h, int oldw, int oldh) {
mCenter.x = w / 2;
mCenter.y = h / 2;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
//We capture any touches not already handled by the ViewPager
// to implement scrolling from a touch outside the pager bounds.
switch (ev.getAction()) {
case MotionEvent.ACTION_DOWN:
mInitialTouch.x = (int)ev.getX();
mInitialTouch.y = (int)ev.getY();
default:
ev.offsetLocation(mCenter.x - mInitialTouch.x, mCenter.y -
mInitialTouch.y);
break;
}
return mPager.dispatchTouchEvent(ev);
}
public void onPageScrolled(int position, float positionOffset, int
positionOffsetPixels) {
//Force the container to redraw on scrolling.
//Without this the outer pages render initially and then stay static
if (mNeedsRedraw) invalidate();
}
public void onPageSelected(int position) { }
public void onPageScrollStateChanged(int state) {
mNeedsRedraw = (state != ViewPager.SCROLL_STATE_IDLE);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent" >
<com.example.testviewpager.PagerContainer
android:id="#+id/pager_container"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#CCC" >
<android.support.v4.view.ViewPager
android:layout_width="150dp"
android:layout_height="100dp"
android:layout_gravity="center_horizontal" />
</com.example.testviewpager.PagerContainer>
</RelativeLayout>
hope help you.