I am currently struggling with giving tinder card animation effect in my view pager.
I am new to animation and dont know much about it.
I am currently using :AndTinder library.
here is my view pager code.
import android.database.Cursor;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.LoaderManager;
import android.support.v4.content.CursorLoader;
import android.support.v4.content.Loader;
import android.support.v4.view.ViewPager;
import android.support.v4.view.ViewPager.OnPageChangeListener;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageButton;
public class ItemPagerFragment extends Fragment implements LoaderManager.LoaderCallbacks<Cursor> {
/**
* The pager widget, which handles animation and allows swiping horizontally to access previous
* and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private CursorPagerAdapter adapter;
private ImageButton favButton;
private ImageButton shareButton;
public ItemPagerFragment() {
// Required empty public constructor
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
System.gc();
// Inflate the layout for this fragment
View rootView = inflater.inflate(R.layout.fragment_item_pager, container, false);
// Instantiate a ViewPager and a PagerAdapter in app.
mPager = (ViewPager) rootView.findViewById(R.id.pager);
getLoaderManager().initLoader(-5, null, this);
mPager.setOffscreenPageLimit(0);
adapter = new CursorPagerAdapter(getFragmentManager(), null);
mPager.setAdapter(adapter);
mPager.setOnPageChangeListener(new OnPageChangeListener() {
// This method will be invoked when a new page becomes selected.
#Override
public void onPageSelected(int position) {
//Toast.makeText(getActivity(),
//"Selected page position: " + ++position, Toast.LENGTH_SHORT).show();
}
// This method will be invoked when the current page is scrolled
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
// Code goes here
}
// Called when the scroll state changes:
// SCROLL_STATE_IDLE, SCROLL_STATE_DRAGGING, SCROLL_STATE_SETTLING
#Override
public void onPageScrollStateChanged(int state) {
// Code goes here
}
});
return rootView;
}
#Override
public void onDestroyView() {
System.gc();
super.onDestroyView();
}
#Override
public void onDestroy() {
super.onDestroy();
}
#Override
public Loader<Cursor> onCreateLoader(int id, Bundle args) {
CursorLoader loader = new CursorLoader(getActivity(),
DataProvider.CONTENT_URI_DATA,
null,
null, // "favorite = 0"
null,
"RANDOM()");
return loader;
}
#Override
public void onLoadFinished(Loader<Cursor> loader, Cursor data) {
adapter.swapCursor(data);
}
#Override
public void onLoaderReset(Loader<Cursor> loader) {
adapter.swapCursor(null);
}
/**
* A simple pager adapter.
*/
private class CursorPagerAdapter extends FragmentStatePagerAdapter {
//HashMap<Integer,ItemDetailFragment> hash = new HashMap<Integer,ItemDetailFragment>();
ItemDetailFragment[] record = new ItemDetailFragment[3];
//HashMap<Integer,ItemDetailFragment> hash = new HashMap<Integer,ItemDetailFragment>(3);
private Cursor mCursor;
public CursorPagerAdapter(FragmentManager fm, Cursor c) {
super(fm);
mCursor = c;
}
#Override
public Fragment getItem(int position) {
if (mCursor.moveToPosition(position)) {
Bundle arguments = new Bundle();
arguments.putLong(ItemDetailFragment.ARG_ITEM_ID, mCursor.getLong(mCursor.getColumnIndex(DataProvider.COL_ID)));
ItemDetailFragment fragment = new ItemDetailFragment();
fragment.setArguments(arguments);
// System.out.println("putting page " + position + " in " + position % 3);
record[position%3] = fragment;
//hash.put(position , fragment);
return fragment;
}
return null;
}
#Override
public int getCount() {
if (mCursor != null) {
return mCursor.getCount();
}
return 0;
}
public void swapCursor(Cursor cursor) {
mCursor = cursor;
try {
notifyDataSetChanged();
}
catch(Exception e)
{
System.out.println("exception caught");
}
}
public void destroyItem(ViewGroup container, int position, Object object){
record[position%3] = null;
super.destroyItem(container,position,object);
}
private ItemDetailFragment getfragment(int position)
{
return record[position%3];
//return hash.get(position);
}
public int getItemPosition(Object object) {
ItemDetailFragment f = (ItemDetailFragment ) object;
int position = mPager.getCurrentItem();
ItemDetailFragment current = adapter.getfragment(position);
if(current.equals(f))
{
int fav = Integer.parseInt(f.data.getFavorite());
if(fav == 1)
f.update(1);
else
f.update(0);
}
return super.getItemPosition(object);
}
//changes to be done here
/*public int getItemPosition(Object object) {
ItemDetailFragment f = (ItemDetailFragment ) object;
int position = mPager.getCurrentItem();
System.out.println("prerna update "+position);
ItemDetailFragment current = adapter.getfragment(position);
if(current.equals(f))
{
System.out.println("prerna got it");
int fav = Integer.parseInt(f.data.getFavorite());
if(fav == 1)
f.update(1);
else
f.update(0);
}
return super.getItemPosition(object);
// return POSITION_NONE;//comment afterwards
}*/
}
}
can anybody please help me to do this.
Related
Good night, I'm new at this, the think that i need to do is this effect using a sroll which conceal a title & displays the following. For example: what happens in the contact list, when you spend the A and B, but still keeps all contacts letter.
I have an example implemented in ios with ViewForHeaderInSection this is what they used to do this effect in instagram this is what I need to do in android.
This is the closest thing I found:
Visit How to implement a scroll view on only part of my layout
Thanks, I apologize for my English is not excellent.
after search and search, i develop my woner layour with propierties...
This class help tu implements a #SlidePage into Fragment.
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
import mijem.bitgray.us.mijem_android.R;
public class FragmentTutorial extends Fragment {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 3;
/**
* The pager widget, which handles animation and allows swiping horizontally
* to access previous and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
ImageView indicator0;
ImageView indicator1;
ImageView indicator2;
List<ImageView> listIndicators = new ArrayList<ImageView>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_viewpager_tutorial, container, false);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
resetIndicators();
listIndicators.get(mPager.getCurrentItem()).setImageResource(
R.drawable.indicador_slide_on);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
mPagerAdapter = new ScreenSlidePagerAdapter(getActivity()
.getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
indicator0 = (ImageView) rootView.findViewById(R.id.indicator0);
indicator1 = (ImageView) rootView.findViewById(R.id.indicator1);
indicator2 = (ImageView) rootView.findViewById(R.id.indicator2);
listIndicators.add(indicator0);
listIndicators.add(indicator1);
listIndicators.add(indicator2);
return rootView;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//TabListener.onResumeFragment(this);
}
public void resetIndicators() {
for (ImageView img : listIndicators)
img.setImageResource(R.drawable.indicador_slide_off);
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects,
* in sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
fragment.setPosition(position);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
enter code here
and the adapter:
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
fragment.setPosition(position);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
enter code here
Code of fragmen pattern
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.view.PagerAdapter;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.ImageView;
import java.util.ArrayList;
import java.util.List;
import mijem.bitgray.us.mijem_android.R;
public class FragmentTutorial extends Fragment {
/**
* The number of pages (wizard steps) to show in this demo.
*/
private static final int NUM_PAGES = 3;
/**
* The pager widget, which handles animation and allows swiping horizontally
* to access previous and next wizard steps.
*/
private ViewPager mPager;
/**
* The pager adapter, which provides the pages to the view pager widget.
*/
private PagerAdapter mPagerAdapter;
ImageView indicator0;
ImageView indicator1;
ImageView indicator2;
List<ImageView> listIndicators = new ArrayList<ImageView>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
// TODO Auto-generated method stub
ViewGroup rootView = (ViewGroup) inflater.inflate(
R.layout.fragment_viewpager_tutorial, container, false);
// Instantiate a ViewPager and a PagerAdapter.
mPager = (ViewPager) rootView.findViewById(R.id.pager);
mPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
resetIndicators();
listIndicators.get(mPager.getCurrentItem()).setImageResource(
R.drawable.indicador_slide_on);
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
mPagerAdapter = new ScreenSlidePagerAdapter(getActivity()
.getSupportFragmentManager());
mPager.setAdapter(mPagerAdapter);
indicator0 = (ImageView) rootView.findViewById(R.id.indicator0);
indicator1 = (ImageView) rootView.findViewById(R.id.indicator1);
indicator2 = (ImageView) rootView.findViewById(R.id.indicator2);
listIndicators.add(indicator0);
listIndicators.add(indicator1);
listIndicators.add(indicator2);
return rootView;
}
#Override
public void onResume() {
// TODO Auto-generated method stub
super.onResume();
//TabListener.onResumeFragment(this);
}
public void resetIndicators() {
for (ImageView img : listIndicators)
img.setImageResource(R.drawable.indicador_slide_off);
}
/**
* A simple pager adapter that represents 5 ScreenSlidePageFragment objects,
* in sequence.
*/
private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
public ScreenSlidePagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
fragment.setPosition(position);
return fragment;
}
#Override
public int getCount() {
return NUM_PAGES;
}
}
}
I am developing an app where the user can type in stuff in edittexts and get to the next view by swiping the screen. The swiping-stuff is handled by a viewpager.
What I want to do is the following:
The user should only be able to swipe when all edittexts are filled. Currently all my edittexts have a TextWatcher whichs sets a boolean value to "true" once every field is filled. When it is true, I want to enable the viewpager, when it isn't, I want to disable it.
I'm using a CustomViewPager with three Fragments. I post my CustomViewPager code:
import android.content.Context;
import android.support.v4.view.ViewPager;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.widget.Toast;
public class CustomViewPager extends ViewPager {
private boolean isPagingEnabled;
public Context context;
public CustomViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
this.isPagingEnabled = true;
this.context = context;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
if (isPagingEnabled) {
return super.onTouchEvent(event);
}
Toast.makeText(context, "Please fill in the details, then swipe !",
Toast.LENGTH_LONG).show();
return false;
}
#Override
public boolean onInterceptTouchEvent(MotionEvent event) {
if (isPagingEnabled) {
return super.onInterceptTouchEvent(event);
}
return false;
}
public void setPagingEnabled(boolean b) {
isPagingEnabled = b;
}
}
PageViewActivity.java
public class PageViewActivity extends FragmentActivity {
MyPageAdapter pageAdapter;
int pageId=0;
public static CustomViewPager pager;
PageListener pageListener;
int currentPage=0;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
List<Fragment> fragments = getFragments();
pageAdapter = new MyPageAdapter(getSupportFragmentManager(), fragments);
pager =(CustomViewPager)findViewById(R.id.viewpager);
pager.setAdapter(pageAdapter);
pager.setPagingEnabled(false);
pageListener = new PageListener();
pager.setOnPageChangeListener(pageListener);
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MyFragmentA.newInstance("Fragment 1"));
fList.add(MyFragmentB.newInstance("Fragment 2"));
fList.add(MyFragmentC.newInstance("Fragment 3"));
return fList;
}
public void next(View v){
if(pageId<=2)
{
pager.setCurrentItem(pageId);
}
pageId++;
}
private class PageListener extends SimpleOnPageChangeListener{
public void onPageSelected(int position) {
Log.i("test", "onPageSelected " + position);
currentPage = position;
}
//Called when the scroll state changes.
public void onPageScrollStateChanged(int state)
{
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels)
{
Log.i("test", "onPageScrolled " + position);
currentPage = position;
}
}
}
My Page Adapter is this:
import java.util.List;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
import android.widget.Toast;
class MyPageAdapter extends FragmentPagerAdapter {
private List<Fragment> fragments;
public MyPageAdapter(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragments = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragments.get(position);
}
#Override
public int getCount() {
return this.fragments.size();
}
}
Finally I post one of my Fragments with the only relevant code:
public class MyFragmentA extends Fragment {
EditText editname;
public static final String EXTRA_MESSAGE = "EXTRA_MESSAGE";
public static final MyFragmentA newInstance(String message)
{
MyFragmentA f = new MyFragmentA();
Bundle bdl = new Bundle(1);
bdl.putString(EXTRA_MESSAGE, message);
f.setArguments(bdl);
return f;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View myFragmentView = inflater.inflate(R.layout.fragment_a, container, false);
editname = (EditText)myFragmentView.findViewById(R.id.name_input);
editname.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(editname.getText().toString().trim().length() == 0) {
// Can I set here isPagingEnabled = false??
Toast.makeText(getActivity(), "SwipeFlag false!", Toast.LENGTH_SHORT).show();
} else if(editname.getText().toString().trim().length() > 0) {
// Can I set here isPagingEnabled = true??
Toast.makeText(getActivity(), "SwipeFlag true!", Toast.LENGTH_SHORT).show();
}
}
});
return myFragmentView;
}
}
I know that the keypoint to block page swipe is to set the flag "isPagingEnabled" to false, but I can't understand what is the best way to set it from a Fragment at runtime.
Ok, I finally found a solution and I post it here.. The best way to block page swipe is to control if edit text is filled inside onPageScrolled in PageViewActivity.java (my MainActivity..):
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
Log.i("test", "onPageScrolled - position = " + position);
currentPage = position;
txt1 = (EditText) findViewById(R.id.name_input);
if(position == 0) {
if(txt1.getText().toString().trim().length() == 0) {
pager.setCurrentItem(0);
} else if(txt1.getText().toString().trim().length() > 0) {
// DO NOTHING
}
}
}
In that way page swipe is not allowed until the edittext field of your fragment is filled.
Another wise way to block page swipe, but ONLY in the right direction is to modify onPageSelected in this way:
boolean inibitFlag = false;
int maxAllowedPage = 1; // .. or you can set this value in your fragment..
public void onPageSelected(int position) {
Log.i("test", "onPageSelected " + position);
if(inibitFlag)
return;
if(position > maxAllowedPage) {
inibitFlag = true;
pager.setCurrentItem(currentPage);
inibitFlag = false;
} else {
currentPage = position;
}
}
Hope this helps someone!!
I am trying to create a fragment that would have a ViewPager. When the said fragment is called and committed, it only displays the first image and it is not swipable. Any thoughts how to achieve this?
Here is the Fragment
import android.os.AsyncTask;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentStatePagerAdapter;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.ViewPager;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
public class HowToFragment extends Fragment {
private ViewPager mViewPager;
private MyAdapter mAdapter;
private int[] image_id = {R.drawable.image_1, R.drawable.image_2, R.drawable.image_3};
private static int image_pos = 0;
public static Fragment newInstance(int pos){
image_pos = pos;
return new HowToFragment();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.fragment_how_to_image, container, false);
v.setBackgroundResource(image_id[image_pos]);
return v;
}
#Override
public void onActivityCreated(Bundle savedInstanceState) {
super.onActivityCreated(savedInstanceState);
mViewPager = new ViewPager(getActivity());
mViewPager.setId(R.id.viewPager_howto);
FragmentManager fm = getFragmentManager();
mAdapter = new MyAdapter(fm);
new setAdapterTask().execute();
}
private class setAdapterTask extends AsyncTask<Void,Void,Void>{
protected Void doInBackground(Void... params) {
return null;
}
#Override
protected void onPostExecute(Void result) {
mViewPager.setAdapter(mAdapter);
}
}
private class MyAdapter extends FragmentStatePagerAdapter{
public MyAdapter(FragmentManager fm) {
super(fm);
// TODO Auto-generated constructor stub
}
#Override
public int getCount() {
return image_id.length;
}
#Override
public Fragment getItem(int position) {
return HowToFragment.newInstance(position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
// TODO Auto-generated method stub
FragmentManager manager = getFragmentManager();
FragmentTransaction ft = manager.beginTransaction();
ft.remove((Fragment) object);
ft.commit();
super.destroyItem(container, position, object);
}
}
}
I doubt you are trying to run this app in Android version less than Honeycomb. What you are trying to achieve is nested fragments. Nested fragment support is available only since jellybean 4.2
Im having a problem here. i downloaded jake wharton. He gave an example of that which works great. But i want is from this i want to change that recent recent recent text to an activity.. so what i did is this , i put a class with .getname in there.. i thought it will be an activity but it convert it to text? this is the code of jake..
Test Fragment.java
package com.simple.viewpage;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.LinearLayout;
import android.widget.LinearLayout.LayoutParams;
import android.widget.TextView;
public final class TestFragment extends Fragment {
private static final String KEY_CONTENT = "TestFragment:Content";
public static TestFragment newInstance(String content) {
TestFragment fragment = new TestFragment();
StringBuilder builder = new StringBuilder();
for (int i = 0; i < 20; i++) {
builder.append(content).append(" ");
}
builder.deleteCharAt(builder.length() - 1);
fragment.mContent = builder.toString();
return fragment;
}
private String mContent = "???";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
if ((savedInstanceState != null) && savedInstanceState.containsKey(KEY_CONTENT)) {
mContent = savedInstanceState.getString(KEY_CONTENT);
}
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
TextView text = new TextView(getActivity());
text.setGravity(Gravity.CENTER);
text.setText(mContent);
text.setTextSize(20 * getResources().getDisplayMetrics().density);
text.setPadding(20, 20, 20, 20);
LinearLayout layout = new LinearLayout(getActivity());
layout.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
layout.setGravity(Gravity.CENTER);
layout.addView(text);
return layout;
}
#Override
public void onSaveInstanceState(Bundle outState) {
super.onSaveInstanceState(outState);
outState.putString(KEY_CONTENT, mContent);
}
}
Test FragmentAdapter.java
package com.simple.viewpage;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentPagerAdapter;
class TestFragmentAdapter extends FragmentPagerAdapter {
protected static final String[] CONTENT = new String[] { "This", "Is", "A", "Test", };
private int mCount = CONTENT.length;
public TestFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public int getCount() {
return mCount;
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
and this is his main activity:
package com.viewpagerindicator.sample;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.view.ViewPager;
import com.viewpagerindicator.TabPageIndicator;
public class SampleTabsDefault extends BaseSampleActivity {
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.simple_tabs);
mAdapter = new GoogleMusicAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (TabPageIndicator)findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
}
class GoogleMusicAdapter extends TestFragmentAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
#Override
public int getCount() {
return SampleTabsDefault.CONTENT.length;
}
#Override
public CharSequence getPageTitle(int position) {
return SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length].toUpperCase();
}
}
}
I change the Content String to this:
private static final String[] CONTENT = new String[] { "Recent", "Artists", "Albums", "Songs", "Playlists", "Genres",ListTest.class.getName() };
Please help.. I want to view an activity and not convert it to text..
Please help.. I want to view an activity and not convert it to text..
You don't view an Activity, you view a Fragment. And you're not converting it, just retrieving its class name and using that as the label in the pager indicator.
I change the Content String to this:
Those are just the labels. The contents are different. The content is retrieved in:
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(SampleTabsDefault.CONTENT[position % SampleTabsDefault.CONTENT.length]);
}
Jake put that code just an example.
It's up to you to switch(position) and return a new Fragment depending on the position you want to appear. I don't use that method (mine is slightly different), but how exactly you want to implement is up to you.
If you have other questions just ask. :-)
edited: a possible example:
static class MyFragmentPagerAdapter extends FragmentPagerAdapter {
public MyFragmentPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return 2;
}
#Override
public Fragment getItem(int position) {
Fragment f;
switch(position) {
case 0:
f= new PlaceDataFragment();
break;
case 1:
f= new PlaceSelectorFragment();
break;
default:
throw new IllegalArgumentException("not this many fragments: " + position);
}
//DebugUtils.debugUI("getView(): " + f.toString());
return f;
}
}
I would like to add or delete pages from my view pager dynamically. Is that possible?
Yes. You can add or delete views dynamically to the PagerAdapter that is supplying them to the ViewPager and call notifyDataSetChanged() from the PagerAdapter to alert the affected ViewPager about the changes. However, when you do so, you must override the getItemPosition(Object) of the PagerAdapter, that tells them whether the items they are currently showing have changed positions. By default, this function is set to POSITION_UNCHANGED, so the ViewPager will not refresh immediately if you do not override this method. For example,
public class mAdapter extends PagerAdapter {
List<View> mList;
public void addView(View view, int index) {
mList.add(index, view);
notifyDataSetChanged();
}
public void removeView(int index) {
mList.remove(index);
notifyDataSetChanged();
}
#Override
public int getItemPosition(Object object)) {
if (mList.contains(object) {
return mList.indexOf(object);
} else {
return POSITION_NONE;
}
}
}
Although, if you simply want to add or remove the view temporarily from display, but not from the dataset of the PagerAdapter, try using setPrimaryItem(ViewGroup, int, Object) for going to a particular view in the PagerAdapter's data and destroyItem(ViewGroup, int, Object) for removing a view from display.
Yes, since ViewPager gets the child Views from a PagerAdapter, you can add new pages / delete pages on that, and call .notifyDataSetChanged() to reload it.
Yes, the code should be like this:
public int addPage(View view, int position) {
if ((position >= 0) && (position < getSize())) {
myPagerAdapter.mListViews.add(position, view);
myPagerAdapter.notifyDataSetChanged();
return position;
} else {
return -1;
}
}
public View removePage(int position) {
if ((position < 0) || (position >= getSize()) || (getSize()<=1)) {
return null;
} else {
if (position == mPager.getCurrentItem()) {
if(position == (getSize()-1)) {
mPager.setCurrentItem(position-1);
} else if (position == 0){
mPager.setCurrentItem(1);
}
}
View tempView = myPagerAdapter.mListViews.remove(position);
myPagerAdapter.notifyDataSetChanged();
return tempView;
}
}
But there is a bug. If the current Item is 0, and to remove page 0, it will not refresh the screen instantly, I haven't found a solution for this.
Here's an alternative solution to this question. My adapter:
private class PagerAdapter extends FragmentPagerAdapter implements
ViewPager.OnPageChangeListener, TabListener {
private List<Fragment> mFragments = new ArrayList<Fragment>();
private ViewPager mPager;
private ActionBar mActionBar;
private Fragment mPrimaryItem;
public PagerAdapter(FragmentManager fm, ViewPager vp, ActionBar ab) {
super(fm);
mPager = vp;
mPager.setAdapter(this);
mPager.setOnPageChangeListener(this);
mActionBar = ab;
}
public void addTab(PartListFragment frag) {
mFragments.add(frag);
mActionBar.addTab(mActionBar.newTab().setTabListener(this).
setText(frag.getPartCategory()));
}
#Override
public Fragment getItem(int position) {
return mFragments.get(position);
}
#Override
public int getCount() {
return mFragments.size();
}
/** (non-Javadoc)
* #see android.support.v4.app.FragmentStatePagerAdapter#setPrimaryItem(android.view.ViewGroup, int, java.lang.Object)
*/
#Override
public void setPrimaryItem(ViewGroup container, int position,
Object object) {
super.setPrimaryItem(container, position, object);
mPrimaryItem = (Fragment) object;
}
/** (non-Javadoc)
* #see android.support.v4.view.PagerAdapter#getItemPosition(java.lang.Object)
*/
#Override
public int getItemPosition(Object object) {
if (object == mPrimaryItem) {
return POSITION_UNCHANGED;
}
return POSITION_NONE;
}
#Override
public void onTabSelected(Tab tab, FragmentTransaction ft) {
mPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(Tab tab, FragmentTransaction ft) { }
#Override
public void onTabReselected(Tab tab, FragmentTransaction ft) { }
#Override
public void onPageScrollStateChanged(int arg0) { }
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) { }
#Override
public void onPageSelected(int position) {
mActionBar.setSelectedNavigationItem(position);
}
/**
* This method removes the pages from ViewPager
*/
public void removePages() {
mActionBar.removeAllTabs();
//call to ViewPage to remove the pages
vp.removeAllViews();
mFragments.clear();
//make this to update the pager
vp.setAdapter(null);
vp.setAdapter(pagerAdapter);
}
}
Code to remove and add dynamically
//remove the pages. basically call to method removeAllViews from ViewPager
pagerAdapter.removePages();
pagerAdapter.addPage(pass your fragment);
After the advice of Peri Hartman, it started to work after I set null to ViewPager adapter and put the adapter again after the views removed. Before this the page 0 doesn't showed its list contents.
I am sure you have created an adapter by extending PageAdapter, so there is one method:
#Override
public void destroyItem(View collection, int position, Object view) {
((ViewPager) collection).removeView((View) view);
}
For detailed example for the same, just go through this example.
First:override the pagerAdapter method "getItemPosition"
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;
}
}
Second:remove the data bind with the adapter.and call adapter.notifydatachanged
#Bind(R.id.pager)
ViewPager pager;
int pos = pager.getCurrentItem();
pager.removeViewAt(pos);
Based on other answers and other resources I've ended with this code.
CustomPagerAdapter:
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentManager;
import android.support.v4.app.FragmentTransaction;
import android.support.v4.view.PagerAdapter;
import android.view.View;
import android.view.ViewGroup;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
public class CustomPagerAdapter extends PagerAdapter {
private List<Fragment> pages = new ArrayList<>();
private Map<Fragment, Integer> fragmentsPosition = new HashMap<>();
private Fragment currentPrimaryItem;
private FragmentManager fragmentManager;
private FragmentTransaction currentTransaction;
public CustomPagerAdapter(FragmentManager fragmentManager) {
this.fragmentManager = fragmentManager;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
Fragment pageFragment = pages.get(position);
String tag = pageFragment.getArguments().getString(MainActivity.FRAGMENT_TAG_ARG);
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
if (fragment.getId() == container.getId()) {
currentTransaction.attach(fragment);
}
else {
fragmentManager.beginTransaction().remove(fragment).commit();
fragmentManager.executePendingTransactions();
currentTransaction.add(container.getId(), fragment, tag);
}
}
else {
fragment = pageFragment;
currentTransaction.add(container.getId(), fragment, tag);
}
if (fragment != currentPrimaryItem) {
fragment.setMenuVisibility(false);
fragment.setUserVisibleHint(false);
}
return fragment;
}
#Override
public int getCount() {
return pages.size();
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
if (currentTransaction == null) {
currentTransaction = fragmentManager.beginTransaction();
}
currentTransaction.detach((Fragment) object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
Fragment fragment = (Fragment) object;
if (fragment != currentPrimaryItem) {
if (currentPrimaryItem != null) {
currentPrimaryItem.setMenuVisibility(false);
currentPrimaryItem.setUserVisibleHint(false);
}
if (fragment != null) {
fragment.setMenuVisibility(true);
fragment.setUserVisibleHint(true);
}
currentPrimaryItem = fragment;
}
}
#Override
public void finishUpdate(ViewGroup container) {
if (currentTransaction != null) {
currentTransaction.commitAllowingStateLoss();
currentTransaction = null;
fragmentManager.executePendingTransactions();
}
}
#Override
public boolean isViewFromObject(View view, Object object) {
return ((Fragment) object).getView() == view;
}
#Override
public int getItemPosition(Object o) {
Integer result = fragmentsPosition.get(o);
if (result == null) {
return PagerAdapter.POSITION_UNCHANGED;
}
return result;
}
// ---------------------------------- Page actions ----------------------------------
public void addPage(Fragment fragment) {
fragmentsPosition.clear();
pages.add(fragment);
notifyDataSetChanged();
}
public void removePage(int position) {
fragmentsPosition.clear();
Fragment pageFragment = pages.get(position);
String tag = pageFragment.getArguments().getString(MainActivity.FRAGMENT_TAG_ARG);
Fragment fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
fragmentsPosition.put(fragment, PagerAdapter.POSITION_NONE);
}
for (int i = position + 1; i < pages.size(); i++) {
pageFragment = pages.get(i);
tag = pageFragment.getArguments().getString(MainActivity.FRAGMENT_TAG_ARG);
fragment = fragmentManager.findFragmentByTag(tag);
if (fragment != null) {
fragmentsPosition.put(fragment, i - 1);
}
}
pages.remove(position);
notifyDataSetChanged();
}
}
MainActivity:
import android.os.Bundle;
import android.support.v4.view.ViewPager;
import android.support.v7.app.AppCompatActivity;
public class MainActivity extends AppCompatActivity {
public static final String FRAGMENT_TAG_ARG = "tag";
private CustomPagerAdapter mCustomPagerAdapter;
private ViewPager mViewPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mCustomPagerAdapter = new CustomPagerAdapter(getSupportFragmentManager());
mCustomPagerAdapter.addPage(MainFragment.newInstance("Main_Title"));
mCustomPagerAdapter.addPage(SecondaryFragment.newInstance("Secondary_Title"));
mViewPager = (ViewPager) findViewById(R.id.container);
mViewPager.setAdapter(mCustomPagerAdapter);
}
}
To remove pages:
mCustomPagerAdapter.removePage(1);
MainFragment:
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.TextView;
public class MainFragment extends Fragment {
public static final String FRAGMENT_TAG = "MainFragment";
public static MainFragment newInstance(String text) {
return newInstance(text, FRAGMENT_TAG);
}
public static MainFragment newInstance(String text, String tag) {
MainFragment fragment = new MainFragment();
Bundle args = new Bundle();
args.putString("text", text);
args.putString(MainActivity.FRAGMENT_TAG_ARG, tag + "_" + fragment.hashCode());
fragment.setArguments(args);
return fragment;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_main, container, false);
TextView textView = (TextView) rootView.findViewById(R.id.section_label);
textView.setText(getArguments().getString("text"));
return rootView;
}
}
SecondaryFragment has the same code.
The layouts are simple ViewPager/Fragment layouts with android.support.v4.view.ViewPager with id container and Fragment TextView with id section_label.
Resources:
dynamically add and remove view to viewpager
How to Remove Fragment from FragmentPagerAdapter?
https://github.com/takaaki7/ArrayPagerAdapter
https://github.com/commonsguy/cwac-pager
you have to set the adapter to viewpager again, then it will refresh the content.
removeView(int pos) in my PagerAdaper
public void removeView(int index) {
imageFileNames.remove(index);
notifyDataSetChanged();
}
wherever I am removing the file I have to do like this
imagePagerAdapter.removeView(currentPosition);
viewPager.setAdapter(imagePagerAdapter);
EDIT:
This below method is effective, you can apply the below one.
public void updateView(int pos){
viewPager.setAdapter(null);
imagePagerAdapter =new ImagePagerAdapter(YOUR_CONTEXT,YOUR_CONTENT);
viewPager.setAdapter(imagePagerAdapter);
viewPager.setCurrentItem(pos);
}
replace YOUR_CONTEXT with your context and your content with your content name i.e. updated list or something.