How to Open a Fragment After Click on ViewPager? - android

public class IMResponseActivity extendsAppCompatActivity implements
ViewPager.OnClickListener {
private static ViewPager viewPager_response;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
try {
setContentView(R.layout.activity_imresponse);
setUI();
setViewPager();
} catch (Exception e) {
e.printStackTrace();
}
}
setViewPager() {
for (int i = 0; i < IMAGES.length; i++)
ImagesArray.add(IMAGES[i]);
viewPager_response = (ViewPager) findViewById(R.id.pager_response);
CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
viewPager_response.setAdapter(new CommonSlideImageAdapter1(IMResponseActivity.this, ImagesArray));
}
public void onClick(View v) {
switch (v.getId()) {
/* case R.id.pager_response:
fragment = new ItemDetailFragment();
//Fragment fragment = new SingleProductFragment();
//Fragment fragment = new ProfileFragment();
// toolbar.setVisibility(View.GONE);
container.setVisibility(View.VISIBLE);
imresponse_layout.setVisibility(View.INVISIBLE);
ft.add(R.id.container_response_details, fragment);
ft.addToBackStack(null);
ft.commit();
break;*/
}
}
// here is my Adapter Code
public class CommonSlideImageAdapter1 extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public CommonSlideImageAdapter1(Context context, ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES=IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, final int position) {
View imageLayout = inflater.inflate(R.layout.common_slideimage_layout1, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
imageView.setClickable(true);
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}

Their is no direct way to implement onItemClick listener and onClickListener in viewpager because it contains different fragments and fragments have their own listeners etc.
so the
first solution for this is implement click listener in fragment
Second solution is to implement your own click listener by extending viewpager class.
to do this there is great solution available
ViewPager OnItemClickListener
hope this will help you.

Related

How to close viewAdapter with button on last image?

what I am trying to do is close the image adapter at the click of a button placed in the third view.
I am setting the views following this tutorial and it works fine: https://www.journaldev.com/10096/android-viewpager-example-tutorial
Now what I am trying to do is close the adapter with a botton in the last view. I get an error that says that points the button: Attempt to invoke virtual method 'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' on a null object reference
I think this is because the button is not on the main layout but on the view layout. so how can I acces it correctly to hide/close the adapter
this is the main
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView3 = findViewById(R.id.textView3);
textView3.setVisibility(View.INVISIBLE);
btnClose=findViewById(R.id.btnClose);
viewPager = (ViewPager) findViewById(R.id.viewpager);
viewPager.setAdapter(new CustomPagerAdapter(this));
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
btnClose.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View arg0) {
viewPager.setVisibility(View.INVISIBLE);
textView3.setVisibility(View.VISIBLE);
}
});
}
This is the adapter
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
public CustomPagerAdapter(Context context) {
mContext = context;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}
This is the model object class
public enum ModelObject {
RED(R.string.red, R.layout.view_red),
BLUE(R.string.blue, R.layout.view_blue),
GREEN(R.string.green, R.layout.view_green);
private int mTitleResId;
private int mLayoutResId;
ModelObject(int titleResId, int layoutResId) {
mTitleResId = titleResId;
mLayoutResId = layoutResId;
}
public int getTitleResId() {
return mTitleResId;
}
public int getLayoutResId() {
return mLayoutResId;
}
}
Just to know how it works I want to hide the adapter and show a textview. Again I think the problem is the button being on another layout, so how can I call it?
Implement your listener in main class & pass it to viewpager. Attach the listener on demand, only the review view.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textView3 = findViewById(R.id.textView3);
textView3.setVisibility(View.INVISIBLE);
viewPager = (ViewPager) findViewById(R.id.viewpager);
View.OnClickListener listener = new View.OnClickListener() {
#Override
public void onClick(View arg0) {
viewPager.setVisibility(View.INVISIBLE);
textView3.setVisibility(View.VISIBLE);
}
}
viewPager.setAdapter(new CustomPagerAdapter(this), listener);
viewPager.setPageTransformer(true, new ZoomOutPageTransformer());
}
public class CustomPagerAdapter extends PagerAdapter {
private Context mContext;
private View.OnClickListener mListener;
public CustomPagerAdapter(Context context, View.OnClickListener listener) {
mContext = context;
mListener = listener;
}
#Override
public Object instantiateItem(ViewGroup collection, int position) {
ModelObject modelObject = ModelObject.values()[position];
LayoutInflater inflater = LayoutInflater.from(mContext);
ViewGroup layout = (ViewGroup) inflater.inflate(modelObject.getLayoutResId(), collection, false);
collection.addView(layout);
if (position == 2) {
View btnClose = layout.findViewById(R.id.btnClose);
btnClose.setOnClickListener(mListener);
}
return layout;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view) {
collection.removeView((View) view);
}
#Override
public int getCount() {
return ModelObject.values().length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public CharSequence getPageTitle(int position) {
ModelObject customPagerEnum = ModelObject.values()[position];
return mContext.getString(customPagerEnum.getTitleResId());
}
}

return activity result from a ViewPager

Am using a ViewPager with adapter to show some pictures (as a gallery) and I need to return the name of the picture when the user click above
my problem that I can not implement onclick from the adapter because I can't return the result to the calling activity, and when I implement the viewAdapter.addOnPageChangeListener I have to wait until the page is changed so if the user clicks on the first pic it well not work
here is my code:
for(int i=0;i<images.length;i++)
imagesArray.add(images[i]);
MyAdapter myAdapter = new MyAdapter(MyImagePicker.this,imagesArray);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(myAdapter);
//CircleIndicator indicator = (CircleIndicator) findViewById(R.id.indicator);
//indicator.setViewPager(mPager);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(mPager, true);
mPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener()
{
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
Toast.makeText(getApplicationContext()," pos : "+position,Toast.LENGTH_LONG).show();
// return result //
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}
class MyAdapter extends PagerAdapter {
private ArrayList<Integer> images;
private LayoutInflater inflater;
private Context context;
public MyAdapter(Context context, ArrayList<Integer> images) {
this.context = context;
this.images=images;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup view, int position) {
View myImageLayout = inflater.inflate(R.layout.slider, view, false);
final ImageView myImage = (ImageView) myImageLayout
.findViewById(R.id.image);
myImage.setImageResource(images.get(position));
myImage.setTag(position+1);
myImage.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
Toast.makeText(context," pos : "+view.getTag(),Toast.LENGTH_LONG).show();
}
});
view.addView(myImageLayout, 0);
return myImageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
}
There are a few approaches you could take:
1) Create a callback interface. In your activity implement the interface (create a listener) and pass it into the adapter's constructor, when the user clicks on an image, pass the image name back to the activity using the callback (mlistener.onImageChosen(view.getTag()).
public interface ImageChosenListener
{
void onImageChosen(String image);
}
2) Use a broadcast from the adapter and have a broadcast receiver in your activity.
try this.
mPager.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
switch(mPager.getCurrentItem()){
case 0: // its position 0
//somthing
break;
.
.
.
}
});
Thanks jt-gilkeson,
I think using a callBack interface is the perfect and the easiest solution :
Here is my answer :
// Create a callBack interface
public interface CallBack {
void callBack(String pos);
}
// The activity hosting my picture gallery
public class MyImagePicker extends Activity implements CallBack {
private static ViewPager mPager;
private static final Integer[] images= {R.drawable.p1,R.drawable.p2,R.drawable.p3,R.drawable.p4};
private ArrayList<Integer> imagesArray = new ArrayList<Integer>();
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.galery_image_chooser);
init();
}
private void init() {
for(int i=0;i<images.length;i++)
imagesArray.add(images[i]);
MyAdapter myAdapter = new MyAdapter(MyImagePicker.this,imagesArray,this);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.setAdapter(myAdapter);
TabLayout tabLayout = (TabLayout) findViewById(R.id.tab_layout);
tabLayout.setupWithViewPager(mPager, true);
}
// Implement the call back function
public void callBack(String pos){
//return back result
Intent intent=new Intent();
intent.putExtra("imgName",pos);
setResult(2,intent);
finish();//finishing activity
}
}

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;
}
}

Android - Pass the parameters between fragments

I developed an android application, as you see in this picture,
I used sherlock action bar for searching, the only problem is that when the user search something in web tab if he/she wants to see the image result, he should type and search again in image tab, is there any way to pass the edittext parameter to other tabs and do searching when user changed the tabs?
MainActivity:
public class MainActivity extends SherlockFragmentActivity implements
TabListener {
private ViewPager viewPager;
private TabsPagerAdapter mAdapter;
private com.actionbarsherlock.app.ActionBar actionBar;
private String[] tabs = { "Sound", "Image", "Web" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
viewPager = (ViewPager) findViewById(R.id.pager);
actionBar = getSupportActionBar();
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowHomeEnabled(false);
mAdapter = new TabsPagerAdapter(getSupportFragmentManager());
actionBar.setHomeButtonEnabled(false);
viewPager.setAdapter(mAdapter);
viewPager.setOffscreenPageLimit(3);
actionBar.setNavigationMode(ActionBar.NAVIGATION_MODE_TABS);
actionBar.addTab(actionBar.newTab().setText(tabs[0])
.setTabListener(this), false);
actionBar.addTab(actionBar.newTab().setText(tabs[1])
.setTabListener(this), false);
actionBar.addTab(actionBar.newTab().setText(tabs[2])
.setTabListener(this), true);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
actionBar.setSelectedNavigationItem(position);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
});
}
#Override
public void onTabSelected(com.actionbarsherlock.app.ActionBar.Tab tab,
android.support.v4.app.FragmentTransaction ft) {
viewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(com.actionbarsherlock.app.ActionBar.Tab tab,
android.support.v4.app.FragmentTransaction ft) {
}
#Override
public void onTabReselected(com.actionbarsherlock.app.ActionBar.Tab tab,
android.support.v4.app.FragmentTransaction ft) {
}
}
Adapter:
public class TabsPagerAdapter extends FragmentPagerAdapter {
public TabsPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int index) {
switch (index) {
case 0:
return new Sound();
case 1:
return new Image();
case 2:
return new Search();
}
return null;
}
#Override
public int getCount() {
return 3;
}
}
Sound Frgment:
public class Sound extends Fragment {
private String URL_ADDRESS, Servlet;
private ListView listview;
private ListViewAdapter adapter;
private List<Spanned> numberlist = new ArrayList<Spanned>();
private List<Ava2> avaList = new ArrayList<Ava2>();
private Boolean isInternetPresent = false;
private ConnectionDetector detector;
private View rootView;
private RelativeLayout loading, layout;
private int counter = 10;
private EditText editText;
private String a = "http://***";
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
rootView = inflater.inflate(R.layout.ava, container, false);
ImageButton voiceSearch = (ImageButton) rootView
.findViewById(R.id.imageButton2);
ImageButton buttonSearch = (ImageButton) rootView
.findViewById(R.id.imageButton1);
listview = (ListView) rootView.findViewById(R.id.listview);
loading = (RelativeLayout) rootView.findViewById(R.id.loading);
layout = (RelativeLayout) rootView.findViewById(R.id.layout);
editText = (EditText) rootView.findViewById(R.id.editText1);
editText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
search();
return true;
}
return false;
}
});
buttonSearch.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
search();
}
});
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view,
int position, long l) {
try {
Intent i = new Intent(getActivity(), Play.class);
startActivity(i);
} catch (Exception e) {
}
}
}
});
return rootView;
}
First,you could write a interface:
public interface OnProfileDataPass {
public String getCurrentSearchword();
public void setCurrentSearchword(String searchword);
}
Then in your fragments:
public class WebFragment extends Fragment {
private OnProfileDataPass dataPasser;
#Override
public void onAttach(Activity activity) {
super.onAttach(activity);
try {
dataPasser = (OnProfileDataPass) activity;
} catch (ClassCastException e) {
throw new ClassCastException(activity.toString() + " must implement OnProfileDataPass");
}
searchword = dataPasser.getCurrentSearchword();
}
}
In your activity:
public class MainActivity implements OnProfileDataPass {
String currentSearchword;
#Override
public String getCurrentSearchword() {
return currentSearchword;
}
#Override
public String setCurrentSearchword(String searchword) {
this.currentSearchword = searchword;
}
}
That's my solution.When you change the tap,you could listen the proper event and set the word with getActivity.setCurrentSearchword(String newword),then you could get the newword in the fragment's dataPasser variable's method getCurrentSearchword() to get the search word. I have test it in my app. Wish that helps you a little.
you should save the value of the editText in your activity and then pass it as an argument when you call your fragment, using the same technique as the one described here: http://developer.android.com/reference/android/app/Fragment.html

how block scrolling in pageAdapter

For example: I have 2 pages in PageAdapter. When I go to second page, I click on button "Lock" and horizontal scrolling is off. I click "Unlock" and again can scrolling. How block scrolling ?
Code:
public class slide extends PagerAdapter
{
List<View> pages = null; // empty list views
public slide (List<View> page)
{
this.pages = page;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object obj)
{
return view.equals(obj);
}
#Override
public Object instantiateItem (View views, int position)
{
View v = pages.get(position);
((ViewPager) views).addView(v, 0);
return v;
}
#Override
public void destroyItem(View views, int position, Object view)
{
((ViewPager) views).removeView((View) view);
}
#Override
public void finishUpdate(View view)
{
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1)
{
}
#Override
public Parcelable saveState()
{
return null;
}
#Override
public void startUpdate(View view)
{
}
In Activity:
List<View> pages = new ArrayList<View>();
View page = inflater.inflate(R.layout.page, null);
TextView textView = (TextView) page.findViewById(R.id.text_view);
textView.setText("Page 1"); // first page
pages.add(page);
page = new surfaceControl(this); // second page with some modul
pages.add(page);
slide pageAdapter = new slide(pages);
ViewPager viewPager = new ViewPager(this);
viewPager.setAdapter(pageAdapter);
viewPager.setCurrentItem(0);

Categories

Resources