issue while hiding a View on ViewPager's fragment - android

am trying to hide and show a View when imageView is being tapped , i have 3 fragments in my ViewPager so the problem is that when am on my first View and i tap the imageView it works fine (my View got hided) but when am on Fragment no. 2 or three and i tap on the imageView it never hides the View its only working on my first fragment , this is my code :
public class MainActivity extends AppCompatActivity {
private static int[] imageArray;
static ImageLoader imageLoader;
static ArrayList<String> urlArray;
static DisplayImageOptions options;
static ProgressBar spinner;
static PhotoViewAttacher mAttacher;
static Boolean isToolBarShown = true;
static Button nextButton , previousButton;
static ViewPager viewPager ;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
urlArray = new ArrayList<>();
urlArray.add("http://i.imgur.com/uLRgvM8.png");
urlArray.add("http://i.imgur.com/LUuJ4FO.png");
urlArray.add("http://i.imgur.com/7SSBNBA.jpg");
// Create global configuration and initialize ImageLoader with this config
DisplayImageOptions defaultOptions = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.imageScaleType(ImageScaleType.EXACTLY)
.displayer(new FadeInBitmapDisplayer(300)).build();
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
getApplicationContext())
.defaultDisplayImageOptions(defaultOptions)
.memoryCache(new WeakMemoryCache()).build();
ImageLoader.getInstance().init(config);
imageLoader = ImageLoader.getInstance();
options = new DisplayImageOptions.Builder().cacheInMemory(true)
.cacheOnDisk(true)
.resetViewBeforeLoading(true).build();
//initialize image view
ImageView imageView = (ImageView) findViewById(R.id.imageView);
ImageFragmentPagerAdapter imageFragmentPagerAdapter = new ImageFragmentPagerAdapter(getSupportFragmentManager());
viewPager = (ViewPager) findViewById(R.id.pager);
viewPager.setOffscreenPageLimit(1);
viewPager.setAdapter(imageFragmentPagerAdapter);
}
public static class ImageFragmentPagerAdapter extends FragmentPagerAdapter {
public ImageFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return urlArray.size();
}
#Override
public Fragment getItem(int position) {
//SwipeFragment fragment = new SwipeFragment();
return SwipeFragment.newInstance(position);
}
}
public static class SwipeFragment extends Fragment {
private int position;
private ImageView imageView;
private RelativeLayout relativeLayout;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
final View swipeView = inflater.inflate(R.layout.swipe_fragment, container, false);
imageView = (ImageView) swipeView.findViewById(R.id.imageView);
spinner = (ProgressBar) swipeView.findViewById(R.id.spinner);
relativeLayout = (RelativeLayout) swipeView.findViewById(R.id.tool_bar);
Bundle bundle = getArguments();
nextButton = (Button)swipeView.findViewById(R.id.next_button);
previousButton = (Button)swipeView.findViewById(R.id.button_previous);
position = bundle.getInt("position");
Toast.makeText(getContext(),"NEW PAGE CALLED",Toast.LENGTH_SHORT).show();
if (isToolBarShown){
relativeLayout.setVisibility(View.VISIBLE);
}else {
relativeLayout.setVisibility(View.GONE);
}
mAttacher = new PhotoViewAttacher(imageView);
// viewPager.OnPageChangeListener(new ViewPager.OnPageChangeListener() {
// #Override
// public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
//
//
// }
//
// #Override
// public void onPageSelected(int position) {
//
// loadImageView(position,imageView);
//
// }
//
// #Override
// public void onPageScrollStateChanged(int state) {
//
// }
// });
previousButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem()-1,true);
}
});
nextButton.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem()+1,true);
}
});
return swipeView;
}
public void loadImageView(int position, final ImageView imageView ){
imageLoader.displayImage(urlArray.get(position), imageView, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
}
#Override
public void onLoadingFailed(String imageUri, View view, FailReason failReason) {
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) {
mAttacher = new PhotoViewAttacher(imageView);
mAttacher.setOnViewTapListener(new PhotoViewAttacher.OnViewTapListener() {
#Override
public void onViewTap(View view, float x, float y) {
if (view == imageView){
if (relativeLayout.getVisibility() == View.VISIBLE){
isToolBarShown = false;
relativeLayout.setVisibility(View.GONE);
}else {
isToolBarShown = true;
relativeLayout.setVisibility(View.VISIBLE);
}
Log.d("OOPS","WHAT THE.., WHAT IS WRONG HERE");
}
}
});
if(mAttacher!=null){
mAttacher.update();
}else{
mAttacher = new PhotoViewAttacher(imageView);
}
spinner.setVisibility(View.GONE);
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
spinner.setVisibility(View.GONE);
}
}, new ImageLoadingProgressListener() {
#Override
public void onProgressUpdate(String imageUri, View view, int current, int total) {
spinner.setVisibility(View.VISIBLE);
spinner.setProgress((current*100)/total);
}
});
}
static SwipeFragment newInstance(int position) {
SwipeFragment swipeFragment = new SwipeFragment();
Bundle bundle = new Bundle();
bundle.putInt("position", position);
swipeFragment.setArguments(bundle);
return swipeFragment;
}
#Override
public void setUserVisibleHint(boolean isVisibleToUser) {
super.setUserVisibleHint(isVisibleToUser);
if (isVisibleToUser) {
// load data here
// if (getView() != null) {
// isViewShown = true;
// // fetchdata() contains logic to show data when page is selected mostly asynctask to fill the data
// loadImageView(position , imageView);
// } else {
// isViewShown = false;
// }
}
}
}}
am trying to hide and show the RelativeView , if anybody knows whats wrong or missing in my code then please do correct me

i think you have to try fragmentstatepageradapter instead of FragmentPagerAdapter. it may help you. you can see the the difference betwwen them here :
Difference between FragmentPagerAdapter and FragmentStatePagerAdapter

You didn't provide all of code, but as you said in comments mAttacher is your static variable from outside of SwipeFragment. I think that
relativeLayout
spinner
imageLoader
are also static members from outside of SwipeFragment. If they are from your R.layout.swipe_fragment layout then you should use each relativeLayout, spinner and imageLoader instance per SwipeFragment.
Now you are swiping to another fragment and you see it. But instances of classes i mentioned above are from another fragment. And that is why it does not working for you as it should. Try to do that. And you can provide more of code.
Good luck!

Setting viewpager offscreenpagelimit mayt help you:)
mViewPager.setoffscreenpagelimit(2)
//2 is important over here.

private final List<Fragment> mFragmentList = new ArrayList<>();
private final List<String> mFragmentTitleList = new ArrayList<>();
public void addFragment(Fragment fragment, String title) {
mFragmentList.add(fragment);
mFragmentTitleList.add(title);
}
//use above function to set fragment

Related

android viewpager like image gallery

im trying to create an image gallery.
i have a ViewPager that each Fragment contains an image (swipable image gallery is what im trying to accomplish).
i also have a GridView that onitemclick triggers the ViewPager in the selected position showing the clicked image.
my problem is that one swipe to right and one swipe to left shows the same image as the clicked one.
ive tried setoffscreenpagelimit with no success.
this is my viewpager activity:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_image_gallery);
helper = new WeddHelper(this,"wedd.db",null,1);
pager = (ViewPager) findViewById(R.id.pager);
pager.setOnPageChangeListener(this);
Intent ing = getIntent();
curr = ing.getIntExtra("curr", 0);
byto = helper.getPhotos();
count = byto.size();
FragmentManager mg = getSupportFragmentManager();
fragments = new Vector<Fragment>();
for(int i = 0; i<count;i++){
fragments.add(Fragment.instantiate(this,GalleryFrag.class.getName()));
}
mAdapter = new FragmentAdapter(getSupportFragmentManager(), fragments, this);
pager.setAdapter(mAdapter);
pager.setOffscreenPageLimit(1);
pager.setCurrentItem(curr);
}
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mCurrentPosition = position;
curr = position;
}
#Override
public void onPageScrollStateChanged(int state) {
}
public int getClicked(){
return curr;
}
public byte[] getPhotoToBeDisplayed(){
return byto.get(curr);
}
}
this is my custom adapter:
public class FragmentAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments=null;
private FragmentManager fragmentManager=null;
private Context context;
public FragmentAdapter(FragmentManager fragmentManager,List<Fragment> fragments, Context context) {
super(fragmentManager);
this.fragments=fragments;
this.fragmentManager=fragmentManager;
this.context = context;
}
#Override
public Fragment getItem(int position) {
return fragments.get(position);
}
#Override
public int getCount() {
return fragments.size();
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object)
{
super.setPrimaryItem(container,0,object);
}
#Override
public void notifyDataSetChanged()
{
super.notifyDataSetChanged();
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
fragmentManager.executePendingTransactions();
fragmentManager.saveFragmentInstanceState(fragments.get(position));
}
public void replaceItem(int position,Fragment fragment)
{
fragments.set(position, fragment);
this.notifyDataSetChanged();
}
}
and this is the fragment:
public class GalleryFrag extends Fragment {
WeddHelper helper;
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.gallery_fragment, container, false);
ImageGallery myActivity = (ImageGallery) getActivity();
int curr = myActivity.getClicked();
byte[] photoToBeDisplayed = myActivity.getPhotoToBeDisplayed();
helper = new WeddHelper(getActivity(),"wedd.db", null, 1);
ArrayList<byte[]> imgs = helper.getPhotos();
Bitmap br = BitmapFactory.decodeByteArray(photoToBeDisplayed,0,photoToBeDisplayed.length);
Bitmap bi = BitmapFactory.decodeByteArray(imgs.get(curr),0,imgs.get(curr).length);
Toast.makeText(getActivity(), curr+"this is from frag", Toast.LENGTH_SHORT).show();
ImageView iv = (ImageView) v.findViewById(R.id.fragImage);
iv.setImageBitmap(br);
return v;
}
}

chrisbanes/PhotoView and UniversalImageLoader, zoom doesn't work

I've a problem by using PhotoViewAttaccher and UniversalImageLoader.
I have a 4 fragments inside swipe fragment, and after UniversalImageloader retrieve pictures, i would zoom it.
this is Activity:
public class FullPics extends FragmentActivity {
private static ViewPager pager;
private String directory;
private String link;
private static String pic_index;
private ImageLoader imageLoader;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_full_pics);
link = this.getIntent().getExtras()
.getString(this.getString(R.string.intent_link));
pic_index = this.getIntent().getExtras()
.getString(this.getString(R.string.extra_which), null);
File cacheDir = StorageUtils.getCacheDirectory(this);
ImageLoaderConfiguration config = new ImageLoaderConfiguration.Builder(
this).memoryCacheExtraOptions(480, 800)
.taskExecutor(AsyncTask.THREAD_POOL_EXECUTOR)
.taskExecutorForCachedImages(AsyncTask.THREAD_POOL_EXECUTOR)
.diskCache(new UnlimitedDiscCache(cacheDir))
.diskCacheFileNameGenerator(new HashCodeFileNameGenerator())
.build();
imageLoader = ImageLoader.getInstance();
imageLoader.init(config);
fragmentManager = getSupportFragmentManager();
pager = (ViewPager) findViewById(R.id.pager);
buildView(link);
}
public static void buildView(String link) {
final FragmentAdapter fragmentAdapter = new FragmentAdapter(
fragmentManager, link);
pager.setAdapter(fragmentAdapter);
pager.setPageMargin(0);
pager.setOffscreenPageLimit(1);
if (pic_index == null) {
pager.setCurrentItem(0);
} else {
pager.postDelayed(new Runnable() {
#Override
public void run() {
pager.setAdapter(fragmentAdapter);
pager.setPageMargin(0);
pager.setOffscreenPageLimit(1);
pager.setCurrentItem(Integer.valueOf(pic_index));
}
}, 100);
}
}
The FragmentPagerAdapter is a standard one, and this is single fragment that will show image:
public class SwipeFragment extends Fragment {
private String link;
private DisplayImageOptions doption;
private PhotoViewAttacher mAttacher;
public SwipeFragment(String link, String img_name) {
this.link = link + "/" + img_name;
doption = new DisplayImageOptions.Builder()
.cacheInMemory(true)
.displayer(new RoundedBitmapDisplayer(20)).build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_swipe, container, false);
ImageLoader imageLoader = ImageLoader.getInstance();
final ImageView picture = (ImageView) view.findViewById(R.id.picture);
mAttacher = new PhotoViewAttacher(picture);
imageLoader.displayImage(link, picture, doption,
new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
// TODO Auto-generated method stub
}
#Override
public void onLoadingComplete(String imageUri, View view,
Bitmap loadedImage) {
Log.i("ATTACCHER", "end");
mAttacher.update();
}
#Override
public void onLoadingCancelled(String imageUri, View view) {
// TODO Auto-generated method stub
}
});
return view;
}
Everithing works, but not zooming. What's wrong?
the zoom worked well when i wasn't using UniversalImageLoader library.
I have been working on something very similar to this. Have you tried attatching the PhotoViewAttacher to the imageview after you have loaded an image into it?
View root = inflater.inflate(R.layout.imageview, container, false);
ivImage = (testImageView) root.findViewById(R.id.ivImageView);
setImageInImageView(ivImage);
mAttacher = new PhotoViewAttacher(ivImage);
I have the mAttacher.update() anytime the image in the imageview changes and it works for me!

OutOfMemory problems in viewpager with imageviews

I have a memory leak (I guess?), somewhere in my app. And i really have no idea where, i have been trying to follow several link explaining different ways to close OOM errors, but without luck.
The thing is, i have a viewpager with 209 pages (data loaded dynamically, and the same single fragment is being used for all 209 pages)
I can scroll through around 20 pages or so before i start getting any memory errors.
All images are loaded by Universal-Image-Loader and are only cached on disc, not in memory.
I am using a FragmentStatePagerAdapter.
Heres the code, i really hope you guys can find something i cant.. Also, if you find anything that should be different, can be optimized or anything, please do tell. :
Activity:
public class MovieInfo extends SherlockFragmentActivity{
MyAdapter mAdapter;
ViewPager mPager;
static ArrayList<Movie> items;
public static class MyAdapter extends FragmentStatePagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public void destroyItem(View collection, int position, Object o) {
View view = (View)o;
((ViewPager) collection).removeView(view);
view = null;
}
#Override
public int getCount() {
return items.size();
}
#Override
public Fragment getItem(int position) {
Fragment f = new MovieInfoFragment();
Bundle args = new Bundle();
args.putParcelable("item", items.get(position));
f.setArguments(args);
return f;
}
}
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.movie_info_pager);
int mIndex = getIntent().getExtras().getInt("index", 0);
DataBaseHelper db = new DataBaseHelper(this);
items = (ArrayList<Movie>) db.getAllMovies();
db.close();
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mPager.setCurrentItem(mIndex);
}
}
Fragment:
public class MovieInfoFragment extends SherlockFragment{
private boolean clearArt = true;
private DisplayImageOptions options;
private Movie movie;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
Bundle data = getArguments();
movie = data.getParcelable("item");
options = new DisplayImageOptions.Builder()
.cacheOnDisc()
.resetViewBeforeLoading()
.bitmapConfig(Bitmap.Config.RGB_565)
.imageScaleType(ImageScaleType.IN_SAMPLE_INT)
.build();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.movie_info, container, false);
if(movie != null){
final ImageView clearArtID = (ImageView) view.findViewById(R.id.Movie_InfoClearArt);
final TextView title = (TextView) view.findViewById(R.id.Movie_InfoTitle);
final TextView genre = (TextView) view.findViewById(R.id.Movie_InfoGenre);
if(clearArt && movie.getClearArt() != null){
clearArtID.setVisibility(ImageView.VISIBLE);
title.setVisibility(TextView.GONE);
genre.setVisibility(TextView.GONE);
}else{
clearArtID.setVisibility(ImageView.GONE);
title.setVisibility(TextView.VISIBLE);
genre.setVisibility(TextView.VISIBLE);
}
ImageView fanart = (ImageView) view.findViewById(R.id.Movie_InfoFanart);
ImageLoader.getInstance().displayImage(movie.getFanart(), fanart, options);
final TextView lineone = (TextView) view.findViewById(R.id.Movie_InfoLineOneText);
final TextView linetwo = (TextView) view.findViewById(R.id.Movie_InfoLineTwoText);
final ImageView cover = (ImageView) view.findViewById(R.id.Movie_InfoCover);
final Movie mov = movie;
ImageLoader.getInstance().displayImage(movie.getThumb(), cover, options);
if(clearArt && movie.getClearArt() != null){
ImageLoader.getInstance().displayImage(movie.getClearArt(), clearArtID, options, new ImageLoadingListener() {
#Override
public void onLoadingStarted(String imageUri, View view) { }
#Override
public void onLoadingFailed(String imageUri, View view,
FailReason failReason) {
clearArtID.setVisibility(ImageView.GONE);
title.setVisibility(TextView.VISIBLE);
genre.setVisibility(TextView.VISIBLE);
title.setText(mov.getTitle().toUpperCase(Locale.ENGLISH));
genre.setText(mov.getGenreString());
lineone.setText(String.valueOf(mov.getDirectorString()));
linetwo.setText("WRITER");
}
#Override
public void onLoadingComplete(String imageUri, View view, Bitmap loadedImage) { }
#Override
public void onLoadingCancelled(String imageUri, View view) { }
});
lineone.setText(movie.getGenreString());
linetwo.setText(movie.getDirectorString());
}else{
title.setText(movie.getTitle().toUpperCase(Locale.ENGLISH));
genre.setText(movie.getGenreString());
lineone.setText(String.valueOf(movie.getDirectorString()));
linetwo.setText("WRITER");
}
TextView rating = (TextView) view.findViewById(R.id.Movie_InfoRating);
rating.setText(movie.getRating() + " / 10");
TextView runtime = (TextView) view.findViewById(R.id.Movie_InfoRuntime);
runtime.setText(movie.getPlaytime()/60 + " min");
TextView year = (TextView) view.findViewById(R.id.Movie_InfoYear);
year.setText(String.valueOf(movie.getYear()));
HorizontalListView listview = (HorizontalListView) view.findViewById(R.id.Movie_InfoActorList);
listview.setAdapter(mAdapter);
TextView plot = (TextView) view.findViewById(R.id.Movie_InfoPlot);
plot.setText(movie.getPlot());
if(movie.getCdart() != null){
ImageView cdArt = (ImageView) view.findViewById(R.id.Movie_InfoCD);
ImageLoader.getInstance().displayImage(movie.getCdart(), cdArt, options);
}
}
return view;
}
}
EDIT:
I do know, that the reason my app is getting OutOfMemory errors is, that it doesn't release the bitmaps in my large viewpager for garbage collection, but how do i get my app to release them? (read: garbage collect) when the are not currently in view, single previous or single next "slide"?
Any help appreciated!
You should probably be calling the super implementation of the destroyItem method

implementing pinch Zoom using ViewPager

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

Call Method From Activity to Fragments

i want to build app with viewpager and display image and text from DB, and i had a button to resize Text to Small,Medium,Big size, but my problem how to make that methode and call it? this is my code
Phrase.java
public void onCreate(Bundle savedInstanceState) {
setContentView(R.layout.phrase);
mViewPager = (ViewPager) findViewById(R.id.viewPager);
mMyFragmentPagerAdapter = new MyFragmentPagerAdapter(getSupportFragmentManager());
mViewPager.setAdapter(mMyFragmentPagerAdapter);
text = (ImageView)findViewById(R.id.ibText);
/* call db and store in arraylist */
....
}
private static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
var = arrayphrase.get(index);
phrase = var.phraseKey;
title_phrase = var.titleKey;
sound_id = var.indexkey;
return PageFragment.newInstance(index,sound_id,phrase,title_phrase);
}
#Override
public void destroyItem(View container, int position, Object object) {
// TODO Auto-generated method stub
super.destroyItem(container, position, object);
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
}
CharSequence[] sizetext = {"Small", "Medium", "Big","Cancel"};
#Override
public void onClick(View v) {
case R.id.ibText:
AlertDialog.Builder listBuilder = new AlertDialog.Builder(Phrase.this);
listBuilder.setItems(sizetext, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(sizetext[item].equals("Big"))
{
sizeText=24;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Medium"))
{
sizeText=20;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Small"))
{
sizeText=16;
onUpdateSize(sizeText);
}
}
});
AlertDialog alertList = listBuilder.create();
alertList.show();
break;
}
PageFragment.java
public class PageFragment extends Fragment {
public static PageFragment newInstance(int index,String sound, String phrase, String title_phrase) {
PageFragment pageFragment = new PageFragment();
Bundle bundle = new Bundle();
bundle.putString("title_phrase", title_phrase);
bundle.putString("sound", sound);
bundle.putString("phrase", phrase);
bundle.putInt("index", index);
pageFragment.setArguments(bundle);
return pageFragment;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment, container, false);
ImageView imageView = (ImageView) view.findViewById(R.id.imageView1);
BitmapFactory.Options options = new BitmapFactory.Options();
options.inSampleSize = 2;
options.inScaled = false;
options.inPreferQualityOverSpeed=true;
options.inJustDecodeBounds = false;
options.inDither = false;
Bitmap bitmap = BitmapFactory.decodeResource(this.getResources(), Imgid[(int)(Math.random()*Imgid.length)], options);
//imageView.setScaleType(ScaleType.FIT_XY);
imageView.setImageBitmap(bitmap);
ScrollView sv = (ScrollView)view.findViewById(R.id.scrollView1);
LinearLayout.LayoutParams lp2= new LinearLayout.LayoutParams((int)(TorasanApp.device_width*0.7), (int) (TorasanApp.device_height*0.65),Gravity.CENTER);
sv.setLayoutParams(lp2);
sv.setBackgroundColor(Color.argb(20, 65, 65, 65));
TextView tvdata = (TextView)view.findViewById(R.id.tvDetailPhrase);
tvdata.setText(getArguments().getString("phrase"));
TextView tvtitle = (TextView)view.findViewById(R.id.tvTitlephrase);
tvtitle.setText(getArguments().getString("title_phrase"));
return view;
}
}
you see in my Phrase when onclick i have onUpdateSize(sizeText) and i want call it to change TextView tvdata fontsize that was in PageFragment.java , so how to make that method and call it? because i try but still cant
In your problem,
You can have a Fragment instance in onClick method for which you want to update textview and from there you can call any method of that class(you have to create such method in Fragment class which will update textview.).
For more understanding refer this link.
in above link Step 10 contain the method calling(viewer.updateUrl(tutUrl);) to fragment class from FragmentActivity class
And in step 8 defination of updateUrl method given which is in Fragment class
In your Fragment's onCreateView, do
mButton.setOnClickListener(new View.OnClickListener() {
AlertDialog.Builder listBuilder = new AlertDialog.Builder(Phrase.this);
listBuilder.setItems(sizetext, new DialogInterface.OnClickListener() {
public void onClick(DialogInterface dialog, int item)
{
if(sizetext[item].equals("Big"))
{
sizeText=24;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Medium"))
{
sizeText=20;
onUpdateSize(sizeText);
}
else if(sizetext[item].equals("Small"))
{
sizeText=16;
onUpdateSize(sizeText);
}
}
});
AlertDialog alertList = listBuilder.create();
alertList.show();
});
Then create accessor methods in your Activity so that your Fragment can retrieve the required fields.

Categories

Resources