It is necessary download the image (on SDcard) and then just use it?
If no, how do this ?
I have image store and images shows in PagerView (images load from internet). I need to select a picture from PagerView and put it on the background (wallpaper).
I can not add a button in ImagePagerActivity for adding image to background.
Error: E/AndroidRuntime(14608): java.lang.RuntimeException: Unable to start activity ComponentInfo{down.load.ascetix/down.load.ascetix.ImagePagerActivity}: java.lang.ClassCastException: down.load.ascetix.ImagePagerActivity.
ImagePagerActivity:
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.EXACT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
#Override
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void finishUpdate(View container) {
}
public int getCount() {
return images.length;
}
public Object instantiateItem(View view, int position) {
final FrameLayout imageLayout = (FrameLayout) inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete() {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View container) {
}
}
}
My .xml file:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip">
<ImageView
android:id="#+id/image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:adjustViewBounds="true" />
<ProgressBar
android:id="#+id/loading"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:visibility="gone" />
</FrameLayout>
Thanks.
You can set your background image this way. It is probably easier.
The Code:
((ImageView)findViewById(R.id.background)).setBackgroundResource(R.drawable.<your image>);
The XML:
<ImageView android:id="#+id/background"
android:layout_width="fill_parent"
android:layout_height="fill_parent"/>
For setting background take a look at this:
http://www.edumobile.org/android/android-beginner-tutorials/setting-an-image-as-a-wallpaper/
Related
I want to display a full image without cut height/width on android.support.v4.view.ViewPager, but when a set image in ImagePagerAdapter adapter the image crops from both sides in my image gallery.
Please help me: how to display a full image in the viewer?
TOTAL_IMAGE=mAllImages.length-1;
viewpager=(ViewPager)findViewById(R.id.image_slider);
handler=new Handler();
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(position);
layout file
<include
android:id="#+id/toolbar"
layout="#layout/toolbar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"/>
<android.support.v4.view.ViewPager
android:id="#+id/image_slider"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_below="#+id/toolbar"
>
</android.support.v4.view.ViewPager>
Java class
int position;
String[] mAllImages,mAllImageCatName,mAllItemId,mAllImageCatDate;
public DatabaseHandler db;
ImageView vp_imageview;
ViewPager viewpager;
int TOTAL_IMAGE;
private SensorManager sensorManager;
private boolean checkImage = false;
private long lastUpdate;
Handler handler;
Runnable Update;
boolean Play_Flag=false;
private Menu menu;
private DatabaseHandler.DatabaseManager dbManager;
String Image_catName,Image_Url,Image_Date;
Bitmap bgr;
DisplayImageOptions options;
Toolbar toolbar;
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.image_slider);
toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
getSupportActionBar().setDisplayHomeAsUpEnabled(true);
getSupportActionBar().setHomeButtonEnabled(true);
db = new DatabaseHandler(this);
dbManager = DatabaseHandler.DatabaseManager.INSTANCE;
dbManager.init(getApplicationContext());
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.ic_launcher)
.showImageOnFail(R.drawable.ic_launcher)
.resetViewBeforeLoading(true)
.cacheOnDisc(true)
.imageScaleType(ImageScaleType.EXACTLY)
.bitmapConfig(Bitmap.Config.RGB_565)
.considerExifParams(true)
.displayer(new FadeInBitmapDisplayer(300))
.build();
Intent i=getIntent();
position=i.getIntExtra("POSITION_ID", 0);
mAllImages=i.getStringArrayExtra("IMAGE_ARRAY");
mAllImageCatName=i.getStringArrayExtra("IMAGE_CATNAME");
mAllImageCatDate=i.getStringArrayExtra("IMAGE_CATDATE");
mAllItemId=i.getStringArrayExtra("ITEMID");
TOTAL_IMAGE=mAllImages.length-1;
viewpager=(ViewPager)findViewById(R.id.image_slider);
handler=new Handler();
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewpager.setAdapter(adapter);
viewpager.setCurrentItem(position);
sensorManager = (SensorManager) getSystemService(SENSOR_SERVICE);
lastUpdate = System.currentTimeMillis();
viewpager.setOnPageChangeListener(new OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
position=viewpager.getCurrentItem();
Image_Url=mAllImages[position];
List<Pojo> pojolist=db.getFavRow(Image_Url);
if(pojolist.size()==0)
{
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_star_outline));
}
else
{
if(pojolist.get(0).getImageurl().equals(Image_Url))
{
menu.getItem(0).setIcon(getResources().getDrawable(R.drawable.ic_star_white));
}
}
}
ImageAdapter class
private class ImagePagerAdapter extends PagerAdapter {
private LayoutInflater inflater;
public ImagePagerAdapter() {
// TODO Auto-generated constructor stub
inflater = getLayoutInflater();
}
#Override
public int getCount() {
return mAllImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
View imageLayout = inflater.inflate(R.layout.viewpager_item, container, false);
assert imageLayout != null;
ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
TextView txt1 = (TextView) imageLayout.findViewById(R.id.txt1);
TextView txt2 = (TextView) imageLayout.findViewById(R.id.txt2);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
txt1.setText(mAllImageCatName[position]);
txt2.setText(mAllImageCatDate[position]);
ImageLoader.getInstance().init(ImageLoaderConfiguration.createDefault(getApplicationContext()));
ImageLoader.getInstance().displayImage(Constant.SERVER_IMAGE_DETAILS+mAllImages[position], imageView, options, new SimpleImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
spinner.setVisibility(View.VISIBLE);
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
String message = null;
switch (failReason.getType()) {
case IO_ERROR:
message = "Input/Output error";
break;
case DECODING_ERROR:
message = "Image can't be decoded";
break;
case NETWORK_DENIED:
message = "Downloads are denied";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(SlideImageActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
}
});
container.addView(imageLayout, 0);
return imageLayout;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
}
In your adapter item set imageview scaletype to fitxy for fitting
android:scaleType="fitXY"
or you can set scale type programmatically also:
ImageView image = findviewbyId(R.id.image);
image.setScaleType(ImageView.ScaleType.FITXY);
You can also check another scale type:
CenterCrop,
CenterInside etc.
ImageView.ScaleType FIT_XY hope it may help try setting scaleType of your inflated ImageView inside adapter or some fragment you are loading in ViewPager.
I'm trying to achieve the following:
I have an item view that displays a ViewPager with images of that item and some other information. When the user taps one of the ViewPager's images, I'd like there to be a transition between the image on the first screen and the same image on another ViewPager in a new Activity.
So far, I've managed to get the basic functionality working but there are a couple of key things that do not work as expected:
The transition from ViewPager A to the second Activity with ViewPager B only works when tapping the image at index 0 or 1 in ViewPager A.
There is a return animation when pressing back from ViewPager B in the new Activity - as long as I do not swipe to another image so the transition is from the full screen mode I'd be displaying in ViewPager B to the same image in ViewPager A. When swiping to another image and pressing back - there's no animation.
Number 1 is happening because the first couple of pages of the ViewPager are instantiated when it's created so the instantiateItem method of the Adapter gets called for each of these and this is where I'm setting the transitionName.
This is proven by the fact that calling this on the ViewPager makes that issue go away and the entry animation works on all screens:
detailPager.setOffscreenPageLimit(largeNumber);
Obviously this is unsustainable, I'd much rather not have such a high off screen limit.
My question is twofold:
How do I achieve the animation for each ViewPager item without keeping all the pages in memory via the above hack?
How can I ensure that a return transition takes place when swiping to another page in ViewPager B?
I've included my code below:
ItemActivity
public class ItemActivity extends AppCompatActivity {
private static final String ITEM_TAG = "item_tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_fragment_container);
ButterKnife.bind(this);
if (savedInstanceState == null) {
attachFragment();
}
}
private void attachFragment() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, ItemFragment.newInstance(), ITEM_TAG)
.commit();
}
#Override
public void onActivityReenter(int resultCode, Intent data) {
super.onActivityReenter(resultCode, data);
ItemFragment fragment = (ItemFragment) getSupportFragmentManager().findFragmentByTag(ITEM_TAG);
if (fragment != null) {
fragment.onReenter(data);
}
}}
ItemFragment - This is where the first ViewPager is
public class ItemFragment extends Fragment implements MyAdapter.MyListener {
public static final String EXTRA_STARTING_ALBUM_POSITION = "extra_starting_item_position";
public static final String EXTRA_CURRENT_ALBUM_POSITION = "extra_current_item_position";
public static final String[] IMAGE_NAMES = {"One", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
private static final int FULL_SCREEN_CODE = 1234;
private Unbinder unbinder;
private Bundle tempReenterState;
private final SharedElementCallback callback = new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (tempReenterState != null) {
int startingPosition = tempReenterState.getInt(EXTRA_STARTING_ALBUM_POSITION);
int currentPosition = tempReenterState.getInt(EXTRA_CURRENT_ALBUM_POSITION);
if (startingPosition != currentPosition) {
String newTransitionName = IMAGE_NAMES[currentPosition];
View newSharedElement = detailPager.findViewWithTag(newTransitionName);
if (newSharedElement != null) {
names.clear();
names.add(newTransitionName);
sharedElements.clear();
sharedElements.put(newTransitionName, newSharedElement);
}
}
tempReenterState = null;
} else {
View navigationBar = getActivity().findViewById(android.R.id.navigationBarBackground);
View statusBar = getActivity().findViewById(android.R.id.statusBarBackground);
if (navigationBar != null) {
names.add(navigationBar.getTransitionName());
sharedElements.put(navigationBar.getTransitionName(), navigationBar);
}
if (statusBar != null) {
names.add(statusBar.getTransitionName());
sharedElements.put(statusBar.getTransitionName(), statusBar);
}
}
}
};
private List<String> images = Arrays.asList("http://wowslider.com/sliders/demo-9/data/images/1293441583_nature_forest_morning_in_the_forest_015232_.jpg",
"http://wowslider.com/sliders/demo-18/data1/images/hongkong1081704.jpg",
"http://www.irishtimes.com/polopoly_fs/1.2614603.1461003507!/image/image.jpg_gen/derivatives/box_620_330/image.jpg",
"http://weknowyourdreams.com/images/sky/sky-05.jpg");
#BindView(R.id.detail_pager)
ViewPager detailPager;
public static ItemFragment newInstance() {
return new ItemFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_image_detail, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ActivityCompat.setExitSharedElementCallback(getActivity(), callback);
detailPager.setAdapter(new MyAdapter(getActivity(), images, this));
}
#Override
public void goFullScreen(final int position, View view) {
Intent intent = FullScreenActivity.newIntent(getActivity(), position, images);
startActivityForResult(intent, FULL_SCREEN_CODE, ActivityOptions.makeSceneTransitionAnimation(getActivity(), view, view.getTransitionName()).toBundle());
}
public void onReenter(Intent data) {
tempReenterState = new Bundle(data.getExtras());
int startingPosition = tempReenterState.getInt(EXTRA_STARTING_ALBUM_POSITION);
int currentPosition = tempReenterState.getInt(EXTRA_CURRENT_ALBUM_POSITION);
if (startingPosition != currentPosition) {
detailPager.setCurrentItem(currentPosition, false);
}
ActivityCompat.postponeEnterTransition(getActivity());
detailPager.post(new Runnable() {
#Override
public void run() {
ActivityCompat.startPostponedEnterTransition(getActivity());
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (unbinder != null) {
unbinder.unbind();
}
}
}
FullScreenActivity - This is where the second ViewPager is housed
public class FullScreenActivity extends AppCompatActivity {
private final SharedElementCallback callback = new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (mIsReturning) {
if (currentImage == null) {
// If shared element is null, then it has been scrolled off screen and
// no longer visible. In this case we cancel the shared element transition by
// removing the shared element from the shared elements map.
names.clear();
sharedElements.clear();
} else if (selectedIndex != mCurrentPosition) {
// If the user has swiped to a different ViewPager page, then we need to
// remove the old shared element and replace it with the new shared element
// that should be transitioned instead.
names.clear();
names.add(currentImage.getTransitionName());
sharedElements.clear();
sharedElements.put(currentImage.getTransitionName(), currentImage);
}
}
}
};
private boolean mIsReturning;
private int mCurrentPosition;
private int selectedIndex;
private static final String ARG_PRESELECTED_INDEX = "arg_preselected_index";
private static final String ARG_GALLERY_IMAGES = "arg_gallery_images";
public static final String KEY_SELECTED_IMAGE_INDEX = "key_selected_image_index";
public static final String KEY_RETAINED_IMAGES = "key_retained_images";
private static final int DEFAULT_SELECTED_INDEX = 0;
private List<String> images;
private ImageAdapter adapter;
private ImageView currentImage;
#BindView(R.id.full_screen_pager)
ViewPager viewPager;
public static Intent newIntent(#NonNull final Context context, final int selectedIndex, #NonNull final List<String> images) {
Intent intent = new Intent(context, FullScreenActivity.class);
intent.putExtra(ARG_PRESELECTED_INDEX, selectedIndex);
intent.putStringArrayListExtra(ARG_GALLERY_IMAGES, new ArrayList<>(images));
return intent;
}
#CallSuper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_full_screen);
ButterKnife.bind(this);
ActivityCompat.postponeEnterTransition(this);
ActivityCompat.setExitSharedElementCallback(this, callback);
if (savedInstanceState == null) {
selectedIndex = getIntent().getIntExtra(ARG_PRESELECTED_INDEX, 0);
mCurrentPosition = selectedIndex;
images = getIntent().getStringArrayListExtra(ARG_GALLERY_IMAGES);
} else {
selectedIndex = savedInstanceState.getInt(KEY_SELECTED_IMAGE_INDEX);
images = savedInstanceState.getStringArrayList(KEY_RETAINED_IMAGES);
}
setupViewPager(selectedIndex, images);
}
private void setupViewPager(final int selectedIndex, List<String> images) {
adapter = new ImageAdapter(this, images);
viewPager.post(new Runnable() {
#Override
public void run() {
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(selectedIndex);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mCurrentPosition = position;
}
});
ActivityCompat.startPostponedEnterTransition(FullScreenActivity.this);
}
});
}
#Override
public void finishAfterTransition() {
mIsReturning = true;
Intent data = new Intent();
data.putExtra(EXTRA_STARTING_ALBUM_POSITION, selectedIndex);
data.putExtra(EXTRA_CURRENT_ALBUM_POSITION, viewPager.getCurrentItem());
setResult(RESULT_OK, data);
super.finishAfterTransition();
}
private class ImageAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final List<String> images;
private ImageLoader<ImageView> imageLoader;
public ImageAdapter(Context context, List<String> images) {
this.imageLoader = new PicassoImageLoader(context);
this.images = images;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
final ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.full_image, container, false);
imageView.setTransitionName(IMAGE_NAMES[position]);
imageView.setTag(IMAGE_NAMES[position]);
imageLoader.loadImage(images.get(position), imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
currentImage = (ImageView) object;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
MyAdapter
public class MyAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final List<String> images;
private final MyListener listener;
private ImageLoader<ImageView> imageLoader;
public interface MyListener {
void goFullScreen(final int position, View selected);
}
public MyAdapter(Context context, List<String> images, MyListener listener) {
this.imageLoader = new PicassoImageLoader(context);
this.layoutInflater = LayoutInflater.from(context);
this.images = images;
this.listener = listener;
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.pager_item_image_thing, container, false);
imageView.setTransitionName(IMAGE_NAMES[position]);
imageView.setTag(IMAGE_NAMES[position]);
if (listener != null) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.goFullScreen(position, imageView);
}
});
}
imageLoader.loadImage(images.get(position), imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
ImageLoader
public interface ImageLoader<T extends ImageView> {
void loadImage(#NonNull final Uri imageSource, #NonNull final T imageView);
void loadImage(#NonNull final String imageSource, #NonNull final T imageView);
}
PicassoImageLoader
public class PicassoImageLoader implements ImageLoader {
private final Context context;
public PicassoImageLoader(#NonNull final Context context) {
this.context = context;
}
#Override
public void loadImage(#NonNull Uri imageSource, #NonNull ImageView imageView) {
Picasso.with(context).load(imageSource).into(imageView);
}
#Override
public void loadImage(#NonNull String imageSource, #NonNull ImageView imageView) {
Picasso.with(context).load(imageSource).into(imageView);
}
}
XML Layouts
fragment_image_detail.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/detail_pager"
android:layout_width="match_parent"
android:layout_height="390dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some other descriptive text about things"/>
</LinearLayout>
layout_full_screen.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/full_screen_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
pager_item_thing.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager_item_image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:foreground="?android:attr/selectableItemBackgroundBorderless"
android:layout_marginBottom="16dp" />
full_image.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/full_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />
I am having some trouble with implementing OnItemClick to the ViewPager.
I would like it so when I click on one of my picture's being displayed by the ViewPager, it displays a toast message just to tell me that this is working.
So far, nothing happens when I click on one of my items when doing this.
Any help would be appreciated!
ViewPager XML:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:ads="http://schemas.android.com/apk/lib/com.google.ads"
android:id="#+id/rellayout"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
</android.support.v4.view.ViewPager>
<com.google.ads.AdView
android:id="#+id/ad"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
ads:adSize="BANNER"
ads:adUnitId="AdIdHere"
ads:loadAdOnCreate="true" >
</com.google.ads.AdView>
</RelativeLayout>
ImageDetail Fragment class:
public class ImageDetailFragment extends Fragment {
private static final String IMAGE_DATA_EXTRA = "extra_image_data";
private String mImageUrl;
private ImageView mImageView;
private ImageFetcher mImageFetcher;
public static ImageDetailFragment newInstance(String imageUrl) {
final ImageDetailFragment f = new ImageDetailFragment();
final Bundle args = new Bundle();
args.putString(IMAGE_DATA_EXTRA, imageUrl);
f.setArguments(args);
return f;
}
public ImageDetailFragment() {
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mImageUrl = getArguments() != null ? getArguments().getString(
IMAGE_DATA_EXTRA) : null;
}
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
context = v.getContext();
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
if (Batmanark.class.isInstance(getActivity())) {
mImageFetcher = ((Batmanark) getActivity()).getImageFetcher();
mImageFetcher.loadImage(mImageUrl, mImageView);
}
}
#Override
public void onDestroy() {
super.onDestroy();
if (mImageView != null) {
ImageWorker.cancelWork(mImageView);
mImageView.setImageDrawable(null);
}
}
}
Fragment detail XML:
<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<ProgressBar
style="?android:attr/progressBarStyleLarge"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center" />
<com.question.ui.RecyclingImageView
android:id="#+id/imageView"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:contentDescription="#string/imageview_description" />
</FrameLayout>
ViewPager Class:
public class Batmanark extends FragmentActivity implements OnClickListener {
private static final String IMAGE_CACHE_DIR = "images";
public static final String EXTRA_IMAGE = "extra_image";
private ImagePagerAdapter mAdapter;
private ImageFetcher mImageFetcher;
private ViewPager mPager;
#TargetApi(11)
#Override
public void onCreate(Bundle savedInstanceState) {
if (BuildConfig.DEBUG) {
Utils.enableStrictMode();
}
super.onCreate(savedInstanceState);
setContentView(R.layout.image_detail_pager);
AdView ad = (AdView) findViewById(R.id.ad);
ad.loadAd(new AdRequest());
final DisplayMetrics displayMetrics = new DisplayMetrics();
getWindowManager().getDefaultDisplay().getMetrics(displayMetrics);
final int height = displayMetrics.heightPixels;
final int width = displayMetrics.widthPixels;
final int longest = (height > width ? height : width) / 2;
ImageCache.ImageCacheParams cacheParams = new ImageCache.ImageCacheParams(
this, IMAGE_CACHE_DIR);
cacheParams.setMemCacheSizePercent(0.25f);
mImageFetcher = new ImageFetcher(this, longest);
mImageFetcher.addImageCache(getSupportFragmentManager(), cacheParams);
mImageFetcher.setImageFadeIn(false);
mAdapter = new ImagePagerAdapter(getSupportFragmentManager(),
Images.imageUrlsBatmanark.length);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setPageMargin((int) getResources().getDimension(
R.dimen.image_detail_pager_margin));
mPager.setOffscreenPageLimit(2);
getWindow().addFlags(LayoutParams.FLAG_FULLSCREEN);
if (Utils.hasHoneycomb()) {
final ActionBar actionBar = getActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayHomeAsUpEnabled(true);
mPager.setOnSystemUiVisibilityChangeListener(new View.OnSystemUiVisibilityChangeListener() {
#Override
public void onSystemUiVisibilityChange(int vis) {
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
actionBar.hide();
} else {
actionBar.show();
}
}
});
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
actionBar.hide();
}
final int extraCurrentItem = getIntent().getIntExtra(EXTRA_IMAGE, -1);
if (extraCurrentItem != -1) {
mPager.setCurrentItem(extraCurrentItem);
}
}
#Override
public void onResume() {
super.onResume();
mImageFetcher.setExitTasksEarly(false);
}
#Override
protected void onPause() {
super.onPause();
mImageFetcher.setExitTasksEarly(true);
mImageFetcher.flushCache();
}
#Override
protected void onDestroy() {
super.onDestroy();
mImageFetcher.closeCache();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case android.R.id.home:
NavUtils.navigateUpFromSameTask(this);
return true;
case R.id.clear_cache:
mImageFetcher.clearCache();
Toast.makeText(this, R.string.clear_cache_complete_toast,
Toast.LENGTH_SHORT).show();
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main_menu, menu);
return true;
}
public ImageFetcher getImageFetcher() {
return mImageFetcher;
}
private class ImagePagerAdapter extends FragmentStatePagerAdapter {
private final int mSize;
public ImagePagerAdapter(FragmentManager fm, int size) {
super(fm);
mSize = size;
}
#Override
public int getCount() {
return mSize;
}
#Override
public Fragment getItem(int position) {
return ImageDetailFragment
.newInstance(Images.imageUrlsBatmanark[position]);
}
}
#TargetApi(11)
#Override
public void onClick(View v) {
final int vis = mPager.getSystemUiVisibility();
if ((vis & View.SYSTEM_UI_FLAG_LOW_PROFILE) != 0) {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_VISIBLE);
} else {
mPager.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LOW_PROFILE);
}
}
}
you need to set click event on view in ImageDetailFragment
private Context context;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View v = inflater.inflate(R.layout.image_detail_fragment,
container, false);
context = v.getContext();
v.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
Toast.makeText(context, "Cilcked..",Toast.LENGTH_SHORT).show();
}
});
mImageView = (ImageView) v.findViewById(R.id.imageView);
return v;
}
I am currently using TouchImageView to allow zooming in and out but now, I need also a View Pager using image view. How do I merge those two together? must I inflate the layout?
this is my viewpager
public class Main extends FragmentActivity implements AdapterView.OnItemSelectedListener, ViewPager.OnPageChangeListener{
private ViewPager viewPager;
String[] mImageIds;
private Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayImage();
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(this);
//gallery = (Gallery) findViewById(R.id.gallery);
//gallery.setAdapter(new ImageAdapter());
//gallery.setOnItemSelectedListener(this);
//textView = (TextView) findViewById(R.id.title);
handler = new Handler();
}
public void displayImage()
{
ArrayList<String> mStringList= new ArrayList<String>();
File strPath = new File(Environment.getExternalStorageDirectory() + "/Covers");
int lists = strPath.listFiles().length;
Log.d("number of items in array ",String.valueOf(lists));
File yourDir = new File(strPath, "");
for (File f : yourDir.listFiles()) {
if (f.isFile())
{
String name = f.getName();
String v = strPath + "/" + name;
mStringList.add(v);
}
}
mImageIds = new String[mStringList.size()];
mImageIds = mStringList.toArray(mImageIds);
for(int i = 0; i < mImageIds.length ; i++){
//Log.d("string is",(mImageIds[i]));
}
}
// gallery item selected
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
updateUI(i);
}
// view pager item selected
public void onPageSelected(int i) {
updateUI(i);
}
private void updateUI(final int i) {
handler.post(new Runnable() {
public void run() {
//gallery.setSelection(i);
viewPager.setCurrentItem(i);
///textView.setText("Photo #" + i);
}
});
}
public void onNothingSelected(AdapterView<?> adapterView) { }
public void onPageScrolled(int i, float v, int i1) { }
public void onPageScrollStateChanged(int i) { }
public class ImageAdapter extends BaseAdapter implements OnTouchListener {
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(Main.this);
imageView.setOnTouchListener(this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
public class EnableDisableViewPager extends ViewPager {
private boolean enabled = true;
public EnableDisableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if(enabled)
return super.onInterceptTouchEvent(arg0);
return false;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mImageIds.length;
}
#Override
public Fragment getItem(final int position) {
return new Fragment() {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = new ImageView(Main.this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
return imageView;
}
};
}
}
}
and its xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout android:layout_height="0px"
android:layout_width="fill_parent"
android:layout_weight="1"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip" />
</FrameLayout>
</LinearLayout>
Create an FragmentActivity whose layout consists of View Pager.
Add a Fragment foreach image whose layout consists of
TouchImageView.
Add these list of fragments to the View pager. Thats it. Pinch Zoom and pager both works.
Like this:
#Override
protected void onStart() {
super.onStart();
List<Fragment> fragments = new Vector<Fragment>();
String url1 = "someurl1.jpg";
Bundle Image1 = new Bundle();
Image1.putString("image_url", url1);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image1));
String url2 = "someurl2.jpg";
Bundle Image2 = new Bundle();
Image2.putString("image_url", url2);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image2));
//and so on.
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.animate();
mPager.setAdapter(this.mPagerAdapter);
}
I am using ViewPager to retrieve images from remote server. Everything is working well, but the problem is I don't know how to implement pinch Zoom in/out function to it. My code is below
public class ImagePagerActivity extends BaseActivity {
private ViewPager pager;
private DisplayImageOptions options;
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.ac_image_pager);
Bundle bundle = getIntent().getExtras();
String[] imageUrls = bundle.getStringArray(Extra.IMAGES);
int pagerPosition = bundle.getInt(Extra.IMAGE_POSITION, 0);
options = new DisplayImageOptions.Builder()
.showImageForEmptyUri(R.drawable.image_for_empty_url)
.cacheOnDisc()
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
pager = (ViewPager) findViewById(R.id.pager);
pager.setAdapter(new ImagePagerAdapter(imageUrls));
pager.setCurrentItem(pagerPosition);
}
protected void onStop() {
imageLoader.stop();
super.onStop();
}
private class ImagePagerAdapter extends PagerAdapter {
private String[] images;
private LayoutInflater inflater;
ImagePagerAdapter(String[] images) {
this.images = images;
inflater = getLayoutInflater();
}
public void destroyItem(View container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public void finishUpdate(View container) {
}
public int getCount() {
return images.length;
}
public Object instantiateItem(View view, int position) {
final View imageLayout = inflater.inflate(R.layout.item_pager_image, null);
final ImageView imageView = (ImageView) imageLayout.findViewById(R.id.image);
final ProgressBar spinner = (ProgressBar) imageLayout.findViewById(R.id.loading);
imageLoader.displayImage(images[position], imageView, options, new ImageLoadingListener() {
public void onLoadingStarted() {
spinner.setVisibility(View.VISIBLE);
}
public void onLoadingFailed(FailReason failReason) {
String message = null;
switch (failReason) {
case IO_ERROR:
message = "Input/Output error";
break;
case OUT_OF_MEMORY:
message = "Out Of Memory error";
break;
case UNKNOWN:
message = "Unknown error";
break;
}
Toast.makeText(ImagePagerActivity.this, message, Toast.LENGTH_SHORT).show();
spinner.setVisibility(View.GONE);
imageView.setImageResource(android.R.drawable.ic_delete);
}
public void onLoadingComplete(Bitmap loadedImage) {
spinner.setVisibility(View.GONE);
Animation anim = AnimationUtils.loadAnimation(ImagePagerActivity.this, R.anim.fade_in);
imageView.setAnimation(anim);
anim.start();
}
public void onLoadingCancelled() {
// Do nothing
}
});
((ViewPager) view).addView(imageLayout, 0);
return imageLayout;
}
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
public void restoreState(Parcelable state, ClassLoader loader) {
}
public Parcelable saveState() {
return null;
}
public void startUpdate(View container) {
}
}
}
if your viewpager is using an imageView then you can use touchImageView
https://github.com/MikeOrtiz/TouchImageView/blob/master/src/com/example/touch/TouchImageView.java
just replace your current imageview with this custom view. goodluck