I having a view pager, which having a textview and initially set to View.INVISIBLE and when the page comes to focus it fades in.
But when i am scrolled to next page and taking previous view the Text View is in Visible state but supposed to be in INVISIBLE state.
I tried with setting the textview to invisble through storing the previous index. But its not resetting the textview.
index = indexCalculator(index);
Log.d("HeadIndex",""+index);
CustomViewPagerAdapter customViewPagerAdapter = (CustomViewPagerAdapter) viewPagerAdapter;
ImageSliderFragment fragment = customViewPagerAdapter.getFragment(index);
fragment.getView().findViewById(R.id.head_data).setVisibility(View.INVISIBLE);
Canyone help me how to set the view to INVISIBLE.
UPDATE Code:
private class CustomViewPagerAdapter extends FragmentStatePagerAdapter {
private Map<Integer, ImageSliderFragment> mPageReferenceMap = new HashMap<>();
public CustomViewPagerAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
ImageSliderFragment imageSliderFragment = new ImageSliderFragment();
Bundle args = new Bundle();
args.putInt(AppConstants.BUNDLE_KEY_FOR_FRAGMENT_POSITION,position);
imageSliderFragment.setArguments(args);
mPageReferenceMap.put(Integer.valueOf(position),imageSliderFragment);
return imageSliderFragment;
}
#Override
public int getCount() {
return AppConstants.NUM_PAGES;
}
#Override
public int getItemPosition(Object object) {
return POSITION_NONE;//super.getItemPosition(object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
return super.instantiateItem(container, position);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
super.destroyItem(container, position, object);
}
public ImageSliderFragment getFragment(int key) {
return mPageReferenceMap.get(key);
}
}
PageChangeListener code:
public class CircularViewPagerHandler implements ViewPager.OnPageChangeListener {
private ViewPager mViewPager;
private int mCurrentPosition;
private int mScrollState;
///For determining swipe direction
private static final float thresholdOffset = 0.5f;
private boolean scrollStarted, checkDirection;
private HeadDataListener headDataListener;
public CircularViewPagerHandler(final ViewPager viewPager,HeadDataListener listener) {
mViewPager = viewPager;
headDataListener = listener;
}
#Override
public void onPageSelected(final int position) {
mCurrentPosition = position;
headDataListener.showHead(position);
Log.d("OnPageSelected",""+position);
}
#Override
public void onPageScrollStateChanged(final int state) {
handleScrollState(state);
mScrollState = state;
if (!scrollStarted && state == ViewPager.SCROLL_STATE_DRAGGING) {
scrollStarted = true;
checkDirection = true;
} else {
scrollStarted = false;
}
}
private void handleScrollState(final int state) {
if (state == ViewPager.SCROLL_STATE_IDLE) {
setNextItemIfNeeded();
}
}
private void setNextItemIfNeeded() {
if (!isScrollStateSettling()) {
handleSetNextItem();
}
}
private boolean isScrollStateSettling() {
return mScrollState == ViewPager.SCROLL_STATE_SETTLING;
}
private void handleSetNextItem() {
final int lastPosition = mViewPager.getAdapter().getCount() - 1;
if(mCurrentPosition == 0) {
mViewPager.setCurrentItem(lastPosition, false);
} else if(mCurrentPosition == lastPosition) {
mViewPager.setCurrentItem(0, false);
}
}
#Override
public void onPageScrolled(final int position, final float positionOffset, final int positionOffsetPixels) {
if (checkDirection) {
if (thresholdOffset > positionOffset) {
AppConstants.SWIPE_DIRECTION = 1;
} else {
AppConstants.SWIPE_DIRECTION = 2;
}
checkDirection = false;
}
}
}
I have implemented a callback to my class
Set the visibility of the view at the XML
android:visibility="gone"
then change the visibity of the view at onPageSelected() method at the CustomPagerAdapter
Related
I'm trying to use viewpager2 in fragment and make each pages clickable.
But all solutions are not working for me.
I tried to make ListPageAdapter to extend RecyclerView.ViewHolder and custom viewHolder by using onCreateViewHolder and onBindViewHolder like recyclerView but it already extended FragmentStateAdapter for making fragment.
How can i make it clickable?
Here is my code
ListPageAdapter.java
public class ListPageAdapter extends FragmentStateAdapter {
public int mCount;
private LayoutInflater mInflate;
private OnListItemClickListener listener;
public ListPageAdapter(FragmentActivity fa, int count) {
super(fa);
mCount = count;
}
#NonNull
#Override
public Fragment createFragment(int position) {
int index = getRealPosition(position);
if(index==0) return new Swipe1();
else if(index==1) return new Swipe2();
else if(index==2) return new Swipe3();
else if(index==3) return new Swipe4();
else return new Swipe5();
}
#Override
public int getItemCount() {
return 2000;
}
public int getRealPosition(int position) { return position % mCount; }
}
TextSearch.java
public class TextSearch extends AppCompatActivity {
private Button submitBtn;
private CircleIndicator3 mIndicator;
private ViewPager2 mPager;
private FragmentStateAdapter pagerAdapter;
private int num_page = 5;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_text_search);
submitBtn = findViewById(R.id.submitBtn);
//ViewPager2
mPager = findViewById(R.id.viewpager);
//Adapter
pagerAdapter = new ListPageAdapter(this, num_page);
//Indicator
mIndicator = findViewById(R.id.indicator);
//ViewPager Setting
mPager.setOrientation(ViewPager2.ORIENTATION_HORIZONTAL);
mPager.setCurrentItem(1000);
mPager.setOffscreenPageLimit(3);
mPager.registerOnPageChangeCallback(new ViewPager2.OnPageChangeCallback() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
super.onPageScrolled(position, positionOffset, positionOffsetPixels);
if (positionOffsetPixels == 0) {
mPager.setCurrentItem(position);
}
}
#Override
public void onPageSelected(int position) {
super.onPageSelected(position);
mIndicator.animatePageSelected(position % num_page);
}
});
final float pageMargin = getResources().getDimensionPixelOffset(R.dimen.pageMargin);
final float pageOffset = getResources().getDimensionPixelOffset(R.dimen.offset);
mPager.setPageTransformer(new ViewPager2.PageTransformer() {
#Override
public void transformPage(#NonNull View page, float position) {
float myOffset = position * -(2 * pageOffset + pageMargin);
if (mPager.getOrientation() == ViewPager2.ORIENTATION_HORIZONTAL) {
if (ViewCompat.getLayoutDirection(mPager) == ViewCompat.LAYOUT_DIRECTION_RTL) {
page.setTranslationX(-myOffset);
} else {
page.setTranslationX(myOffset);
}
} else {
page.setTranslationY(myOffset);
}
}
});
submitBtn.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
mPager.setAdapter(pagerAdapter);
mIndicator.setViewPager(mPager);
mIndicator.createIndicators(num_page, 0);
String sendText = textLine.getText().toString();
Log.d("calling", sendText);
FileUploadUtils.sendText(sendText);
}
});
}
}
You can use the same approach as for a common fragments. In Fragment(page of a pager) Override onAttach method and implement it like this.
#Override
public void onAttach(#NotNull Context context) {
super.onAttach(context);
try {
pageClickListener = ((PageClickListener) context);
} catch (Exception e) {
Log.e("SwipeFragment", "Root activity must implement PageClickListener");
}
}
And a root activity have to implement your listener.
public class MainActivity implements PageClickListener
I use ViewPager and PageAdapter to show my data and the ViewPager has its PageTransformer, it works well and now I need to update data and UI when sliding to a new item but the problem is when I slide to the new item and call `adapter.notifyDataSetChanged(), my data and UI do updated but my PageTransformer do not work.
Here is my code:
mAdapter = new DynamicsCardAdapter(getContext(), mList);
mViewPager.setPageTransformer(true, new ZoomOutPageTransformer2());
mViewPager.setPageMargin(-(int) (width * 0.30));
mViewPager.setAdapter(mAdapter);
Adapter:
public class DynamicsCardAdapter extends PagerAdapter {
private Context mContext;
private List<ChildDynamicsInfo> mList;
private int mPosition = -1;
private int mChildCount = 0;
public DynamicsCardAdapter(Context context, List<ChildDynamicsInfo> list) {
mContext = context;
mList = list;
}
#Override
public int getCount() {
return mList.size();
}
#Override
public boolean isViewFromObject(#NonNull View view, #NonNull Object object) {
return view == object;
}
#NonNull
#Override
public Object instantiateItem(#NonNull ViewGroup viewGroup, int position) {
View convertView = LayoutInflater.from(mContext).inflate(R.layout.item_parent_dynamics_card, viewGroup, false);
textName = (TextView) convertView.findViewById(R.id.student_name);
textName.setText(mList.get(position).name);
viewGroup.addView(convertView);
return convertView;
}
#Override
public void destroyItem(#NonNull ViewGroup container, int position, #NonNull Object object) {
container.removeView((View) object);
}
#Override
public void notifyDataSetChanged() {
mChildCount = getCount();
super.notifyDataSetChanged();
}
#Override
public int getItemPosition(#NonNull Object object) {
//return POSITION_NONE;
if ( mChildCount > 0) {
mChildCount --;
return POSITION_NONE;
}
return super.getItemPosition(object);
}
}
PageTransformer:
public class ZoomOutPageTransformer2 implements ViewPager.PageTransformer {
private static final float MAX_ROTATE = 30.0f;
public void transformPage(View view, float position) {
int pageWidth = view.getWidth();
int pageHeight = view.getHeight();
float currentRotate = position * MAX_ROTATE;
if (position < 0) {
view.setPivotX(pageWidth / 2);
view.setPivotY(view.getHeight());
view.setRotation(currentRotate);
} else if (position <= 1) {
view.setPivotX(pageWidth / 2);
view.setPivotY(view.getHeight());
view.setRotation(currentRotate);
} else if (position == 0) {
view.setRotation(0);
}
}
}
Update data:
mViewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
mList.get(position).isRead = true;
mAdapter.notifyDataSetChanged();
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
I just want to update my UI when sliding to a new item and make sure that my PageTransformer work well, I used to try :
mViewPager.setAdapter(mAdapter);
mViewPager.setCurrentItem(position);
but because I update UI on onPageSelected() so it will cause StackOverFlow.
I've seen quite a few posts about this "issue" with RecyclerView, but I can't manage to fix it.
Every time I scroll, my custom CheckBoxes (starStyle) keep turning on/off.
I've tried to follow other solutions here on Stack, but none seems to do the job for me.
Just to explain the structure of my app, I've a long list (each item has a StarStyle CheckBox): when I click on an item, the app takes me in the Details Page for that item, where I can set the CheckBox, too. I managed to bind the list's checkbox and the one in the detail page, but I still having this annoying problem.
Here my code for the ListFragment:
public class PetrolStationListFragment extends Fragment {
private RecyclerView mPetrolStationRecyclerView;
private PetrolStationAdapter mAdapter;
private int itemPosition;
private int mLastAdapterClickPosition = -1;
private List<Boolean> mCheckState = new ArrayList<>();
public static boolean toBeCreated;
private static final String ARG_POSITION = "position";
// Design pattern to instantiate a new fragment.
public static PetrolStationListFragment newInstance(int position) {
PetrolStationListFragment fragment = new PetrolStationListFragment();
Bundle args = new Bundle();
args.putInt(ARG_POSITION, position);
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_petrol_station_list, container, false);
mPetrolStationRecyclerView = (RecyclerView) view.findViewById(R.id.petrol_recycler_view);
mPetrolStationRecyclerView.setLayoutManager(new LinearLayoutManager(getActivity()));
updateUI();
return view;
}
#Override
public void onResume() {
super.onResume();
updateUI();
}
private void updateUI() {
PetrolStationDAO petrolStationDAO = PetrolStationDAO.get(getActivity());
List<PetrolStation> petrolStations = petrolStationDAO.getPetrolStations();
if (mAdapter == null || toBeCreated) {
mAdapter = new PetrolStationAdapter(petrolStations);
mPetrolStationRecyclerView.setAdapter(mAdapter);
toBeCreated = false;
} else {
if (mLastAdapterClickPosition < 0) {
mAdapter.setPetrolStations(petrolStations);
mAdapter.notifyDataSetChanged();
} else {
mAdapter.notifyItemChanged(mLastAdapterClickPosition);
mLastAdapterClickPosition = -1;
}
mAdapter.notifyItemChanged(itemPosition);
}
}
private class PetrolStationHolder extends RecyclerView.ViewHolder implements View.OnClickListener {
private PetrolStation mPetrolStation;
private TextView mNameTextView;
private TextView mAddressTextView;
private TextView mDistanceTextView;
private CheckBox mCheckBox;
private int mPosition;
public PetrolStationHolder(View itemView) {
super(itemView);
itemView.setOnClickListener(this);
mNameTextView = (TextView) itemView.findViewById(R.id.list_item_station_name_text_view);
mAddressTextView = (TextView) itemView.findViewById(R.id.list_item_station_address_text_view);
mDistanceTextView = (TextView) itemView.findViewById(R.id.list_item_station_distance_text_view);
mCheckBox = (CheckBox) itemView.findViewById(R.id.checkbox);
}
public void bindPetrolStation(PetrolStation petrolStation, int position) {
mPetrolStation = petrolStation;
mNameTextView.setText(mPetrolStation.getName());
mAddressTextView.setText("Via Verdi, 19/A");
mDistanceTextView.setText("300 meters");
mPosition = position;
//mCheckBox.setChecked(mPetrolStation.isFavourite());
mCheckBox.setChecked(mCheckState.get(mPosition));
Log.d("BIND_POSITION", "position: " + mPosition + " / status: " + mCheckState.get(mPosition));
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
boolean boxChecked = mPetrolStation.isFavourite();
Log.d("BOX_CHECKED_POSITION", "boxChecked: " + boxChecked);
if (boxChecked) {
mPetrolStation.setFavourite(false);
} else {
mPetrolStation.setFavourite(true);
}
if (boxChecked) {
mCheckState.set(mPosition, false);
} else {
mCheckState.set(mPosition, true);
}
Log.d("CHECK_POSITION", "mCheckState: " + mCheckState);
// TODO: DB connection.
// PetrolStationDAO.get(getActivity()).updateItem(mCrime);
}
});
}
#Override
public void onClick(View v) {
itemPosition = mPetrolStationRecyclerView.getChildAdapterPosition(v);
Intent intent = PetrolStationPagerActivity.newIntent(getActivity(), mPetrolStation.getId());
startActivity(intent);
}
}
private class PetrolStationAdapter extends RecyclerView.Adapter<PetrolStationHolder> {
private List<PetrolStation> mPetrolStations;
public PetrolStationAdapter(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
for (int i = 0; i < mPetrolStations.size(); i++) {
mCheckState.add(false);
}
}
#Override
public PetrolStationHolder onCreateViewHolder(ViewGroup parent, int viewType) {
LayoutInflater layoutInflater = LayoutInflater.from(getActivity());
View view = layoutInflater.inflate(R.layout.list_item_petrol_station, parent, false);
return new PetrolStationHolder(view);
}
#Override
public void onBindViewHolder(PetrolStationHolder holder, int position) {
PetrolStation petrolStation = mPetrolStations.get(position);
holder.bindPetrolStation(petrolStation, position);
// holder.setIsRecyclable(false);
}
#Override
public int getItemCount() {
return mPetrolStations.size();
}
public void setPetrolStations(List<PetrolStation> petrolStations) {
mPetrolStations = petrolStations;
}
}
}
Here the one for the DetailsFragment:
public class PetrolStationFragment extends Fragment {
private static final String ARG_PETROL_STATION_ID = "petrol_station_id";
private PetrolStation mPetrolStation;
private TextView mInfo;
private CheckBox mCheckBox;
private static TabLayout mTabLayout;
private static ViewPager mViewPager;
private static int intItems = 2;
// Navigation Tab constants.
private static final int SELF_SERVICE_POSITION = 0;
private static final int FULL_SERVICE_POSITION = 1;
// Design pattern to instantiate a new fragment.
public static PetrolStationFragment newInstance(long petrolStationId) {
Bundle args = new Bundle();
args.putLong(ARG_PETROL_STATION_ID, petrolStationId);
PetrolStationFragment fragment = new PetrolStationFragment();
fragment.setArguments(args);
return fragment;
}
/********************************************************/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
long mId = getArguments().getLong(ARG_PETROL_STATION_ID);
mPetrolStation = PetrolStationDAO.get(getActivity()).getPetrolStation(mId);
}
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceStace) {
View view = inflater.inflate(R.layout.fragment_petrol_station, container, false);
mInfo = (TextView) view.findViewById(R.id.petrol_station);
mCheckBox = (CheckBox) view.findViewById(R.id.checkbox);
mInfo.setText(mPetrolStation.getName());
mCheckBox.setChecked(mPetrolStation.isFavourite());
// TODO: to fix.
mCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isFavourite) {
mPetrolStation.setFavourite(isFavourite);
}
});
// Setup Views.
mTabLayout = (TabLayout) view.findViewById(R.id.pager_header);
mViewPager = (ViewPager) view.findViewById(R.id.pager);
// Set an Adapter for the View Pager.
TabPagerAdapter tabPagerAdapter = new TabPagerAdapter(getChildFragmentManager());
mViewPager.setAdapter(tabPagerAdapter);
mTabLayout.setupWithViewPager(mViewPager);
mViewPager.setCurrentItem(SELF_SERVICE_POSITION);
mTabLayout.addOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
int flag;
#Override
public void onTabSelected(TabLayout.Tab tab) {
mViewPager.setCurrentItem(tab.getPosition());
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
}
});
mInfo.addTextChangedListener(new TextWatcher() {
#Override
public void beforeTextChanged(CharSequence charSequence, int i, int i1, int i2) {
}
#Override
public void onTextChanged(CharSequence charSequence, int i, int i1, int i2) {
mPetrolStation.setName(charSequence.toString());
}
#Override
public void afterTextChanged(Editable editable) {
}
});
return view;
}
class TabPagerAdapter extends FragmentPagerAdapter {
public TabPagerAdapter(FragmentManager fm) {
super(fm);
}
// Return fragment with respect to position.
#Override
public Fragment getItem(int position) {
Fragment fragment;
switch (position) {
case SELF_SERVICE_POSITION: {
fragment = SelfServiceFragment.newInstance();
return fragment;
}
case FULL_SERVICE_POSITION: {
fragment = FullServiceFragment.newInstance();
return fragment;
}
}
return null;
}
#Override
public int getCount() {
return intItems;
}
// This method returns the title of the tab according to its position.
#Override
public CharSequence getPageTitle(int position) {
switch (position) {
case SELF_SERVICE_POSITION: {
String mSelfService = getResources().getString(R.string.self_service);
return mSelfService;
}
case FULL_SERVICE_POSITION: {
String mFullService = getResources().getString(R.string.full_service);
return mFullService;
}
}
return null;
}
}
}
Any hints about how to solve this issue?
Am I missing some kind of check?
Use a List of boolean type to hold the state of the checkbox. By default fill your collection with a false value.
When you select a checkbox change the state of the map using the set method
As you know When you scroll there will be a call to your adapter there you read the value from the map using get and set it to checkbox
List < Boolean > checkstate = new ArrayList < Boolean > ();
// Inside the adapter constructor
for (i = 0; i < itemSize; i++) {
checkstate.add(false);
}
Inside your Viewholder add below Line what it does is whatever the updated value of checkbox will set to your checkbox. Initially all the Items will be false
yourCheckbox.setChecked(checkstate.get(position));
Now inside onCheckedChanged Listener
if (boxchecked) {
checkstate.set(position, true);
} else {
checkstate.set(position, false);
}
I'm using the MainActivity's SearchView here to filter the listview which is showing under tabs but there is an issue of the state of Fragment.
It filters perfectly but when I select first Tab(ADVISORY), then it filters the child of this Tab. And after selecting next Tab(TOP ADVISORY), it filters all listview of the child of this tab but it stops filtering in previous Tab (ADVISORY). And at last I move to the EXPERTVIEW it works only for it not for others.
After lots of debugging I found that it doesn't get destroy when we select another Parent Tab so now I wanna know how I can remove a fragment from its adapter on unselected and reselect on selected again.
MainTabFragment.java
public class MainTabFragment extends Fragment {
public static int position_child_tab = 0, three_childs_tab_position = 0;
static int count = -1, index = 0;
int position_tab = 0;
Bundle args;
int Current_tab = 0;
public static MyTabLayout myTabLayout;
private static MainTabFragment sMainTabFragment;
public static NonSiwpablePager pager;
private Fragment mFragment;
SharedPreferences pref;
private static final int NUM_ITEMS = 2;
List<Integer> TABLE;
public MainTabFragment() {
// Required empty public constructor
}
public static MainTabFragment getInstance() {
return sMainTabFragment;
}
/**
* Use this factory method to create a new instance of
* this fragment using the provided parameters.
*
* #param param1 Parameter 1.
* #param param2 Parameter 2.
* #return A new instance of fragment MainTabFragment.
*/
// TODO: Rename and change types and number of parameters
public static MainTabFragment newInstance(String param1, String param2) {
return new MainTabFragment();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
args = getArguments();
if (args != null && args.containsKey("pos_next"))
position_tab = args.getInt("pos_next");
if (args != null && args.containsKey("pos_end"))
position_child_tab = args.getInt("pos_end");
if (position_child_tab != 3) {
three_childs_tab_position = position_child_tab;
} else {
three_childs_tab_position = 0;
}
args = new Bundle();
args.putInt("pos_end", position_child_tab);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.main_tab_fragment, container, false);
myTabLayout = (MyTabLayout) view.findViewById(R.id.mainTabLayout);
pager = (NonSiwpablePager) view.findViewById(R.id.pager);
final ViewPagerAdapter mAdapter = getViewPagerAdapter();
pager.setAdapter(mAdapter);
myTabLayout.setupWithViewPager(pager);
for (int i = 0; i < mAdapter.getCount(); i++) {
View customView = mAdapter.getCustomeView(getActivity(), i);
myTabLayout.getTabAt(i).setCustomView(customView);
}
pager.setCurrentItem(position_tab);
pager.setOffscreenPageLimit(NUM_ITEMS-1);
changeTab();
final Fragment fragment = getFragmentManager().findFragmentByTag("TOP");
if (fragment != null) {
pager.setCurrentItem(position_tab);
}
index = pager.getCurrentItem();
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
// ViewPagerAdapter adapter = ((ViewPagerAdapter)pager.getAdapter());
final Fragment fragment22 = mAdapter.getRegisteredFragment(pager.getCurrentItem());
pager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int arg0) {
// TODO Auto-generated method stub
pref = getActivity().getPreferences(0);
SharedPreferences.Editor edt = pref.edit();
edt.putInt("facebook_id", pager.getCurrentItem());
edt.commit();
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
myTabLayout.setOnTabSelectedListener(new TabLayout.OnTabSelectedListener() {
#Override
public void onTabSelected(TabLayout.Tab tab) {
pager.setCurrentItem(tab.getPosition());
//Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabUnselected(TabLayout.Tab tab) {
// mAdapter.destroyAllItem();
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
#Override
public void onTabReselected(TabLayout.Tab tab) {
// Log.e("Fragment", fragment + "" +pager.getCurrentItem() + fragment22);
}
});
return view;
}
public void changeTab() {
Current_tab = pager.getCurrentItem();
}
#Override
public void onViewCreated(View view, Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
myTabLayout.getTabAt(position_tab).getCustomView().setSelected(true);
}
public void setCurrentItem(int item) {
pager.setCurrentItem(item);
}
private ViewPagerAdapter getViewPagerAdapter() {
ViewPagerAdapter mAdapter = new ViewPagerAdapter(getChildFragmentManager());
String title_arr[] = {"ADVISORY", "TOP ADVISORS", "EXPERT VIEW"};
for (int i = 0; i < title_arr.length; i++) {
Map<String, Object> map = new Hashtable<>();
map.put(ViewPagerAdapter.KEY_TITLE, title_arr[i]);
if (i == 0) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, AdvisoryPagerFragment.newInstance());
AdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 1) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, TopAdvisoryPagerFragment.newInstance());
TopAdvisoryPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
} else if (i == 2) {
map.put(ViewPagerAdapter.KEY_FRAGMENT, ExperViewPagerFragment.newInstance());
ExperViewPagerFragment.newInstance().setTargetFragment(this, getTargetRequestCode());
}
mAdapter.addFragmentAndTitle(map);
}
return mAdapter;
}
public static class ViewPagerAdapter extends FragmentStatePagerAdapter {
private static final String KEY_TITLE = "fragment_title";
private static final String KEY_FRAGMENT = "fragment";
boolean abc = false;
private int[] drawables = new int[]{R.drawable.advisory_selector, R.drawable.top_advisors_selector, R.drawable.expertview_selector};
private List<Map<String, Object>> maps = new ArrayList<>();
private Fragment mCurrentFragment;
SparseArray<Fragment> registeredFragments = new SparseArray<Fragment>();
public ViewPagerAdapter(FragmentManager fm) {
super(fm);
}
public View getCustomeView(Context context, int pos) {
View mView = LayoutInflater.from(context).inflate(R.layout.custom_tab_view, null);
TextView mTextView = (TextView) mView.findViewById(R.id.textView);
mTextView.setTypeface(Typeface.createFromAsset(context.getAssets(), "fonts/ufonts.com_cambria.ttf"));
ImageView mImageView = (ImageView) mView.findViewById(R.id.imageView2);
mImageView.setTag(pos);
/*if(count >0)
{
Toast.makeText(context,"Count Is "+count,Toast.LENGTH_SHORT).show();
mImageView = (ImageView) mImageView.getTag(0);
mImageView.setSelected(false);
}
*/
mImageView.setImageResource(drawables[pos]);
mTextView.setText(getPageTitle(pos));
return mView;
}
public void addFragmentAndTitle(Map<String, Object> map) {
maps.add(map);
}
#Override
public CharSequence getPageTitle(int position) {
return (CharSequence) maps.get(position).get(KEY_TITLE);
}
#Override
public Fragment getItem(int position) {
Log.e("Fragmentss", (Fragment) maps.get(position).get(KEY_FRAGMENT) + "");
return (Fragment) maps.get(position).get(KEY_FRAGMENT);
}
public Fragment getCurrentFragment() {
return mCurrentFragment;
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
if (mCurrentFragment != object) {
mCurrentFragment = (Fragment) object;
}
super.setPrimaryItem(container, position, object);
}
#Override
public int getCount() {
return maps.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Fragment fragment = (Fragment) super.instantiateItem(container, position);
registeredFragments.put(position, fragment);
return fragment;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
registeredFragments.remove(position);
super.destroyItem(container, position, object);
}
public Fragment getRegisteredFragment(int position) {
return registeredFragments.get(position);
}
}
}
I am using PageIndicator with ViewPager , but only the page title appears. The page icons don't appear. Does any one know why? Here is my adapter.
class GoogleMusicAdapter extends FragmentPagerAdapter implements IconPagerAdapter {
public GoogleMusicAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return TestFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public CharSequence getPageTitle(int position) {
return CONTENT[position % CONTENT.length].toUpperCase();
}
#Override public int getIconResId(int index) {
return ICONS[index];
}
#Override
public int getCount() {
return CONTENT.length;
}
}
My Adapter
public class FavouritePagerAdapter extends PagerAdapter implements
IconPagerAdapter, ViewPager.OnPageChangeListener {
private static final int FAVOURITE_EPISODE_INDEX = 0;
private static final int FAVOURITE_SHOW_INDEX = 1;
private static final int NUMBER_OF_PAGES = 2;
private static final String[] FAVOURITE_TITLES = {
Util.getApplicationContext().getString(
R.string.favourite_title_episode),
Util.getApplicationContext().getString(
R.string.favourite_title_show) };
public static final String TAG_EMPTY_EPISODE = "emtpy_episode";
public static final String TAG_EMPTY_SHOW = "empty_show";
public static final String TAG_LOADING_EPISODE = "loading_epsiode";
public static final String TAG_LOADING_SHOW = "loading_show";
WeakReference<Activity> acitivity;
WeakReference<FavouriteFragment> favouriteFragment;
FavouriteEpisodeAdapter mFavouriteEpisodeAdapter;
FavouriteShowAdapter mFavouriteShowAdapter;
public FavouritePagerAdapter(FavouriteFragment fr, Activity a,
ArrayList<EpisodeInfo> episode, ArrayList<ShowData> show) {
super();
this.favouriteFragment = new WeakReference<FavouriteFragment>(fr);
this.acitivity = new WeakReference<Activity>(a);
mFavouriteEpisodeAdapter = new FavouriteEpisodeAdapter(a,
R.id.textView1, episode);
mFavouriteShowAdapter = new FavouriteShowAdapter(a, R.id.textView1,
show);
}
#Override
public CharSequence getPageTitle(int position) {
Log.d("getPageTitle", FAVOURITE_TITLES[position]);
return FAVOURITE_TITLES[position];
}
#Override
public int getIconResId(int index) {
return R.drawable.ic_action_search;
}
#Override
public int getCount() {
return NUMBER_OF_PAGES;
}
#Override
public Object instantiateItem(View container, int position) {
View v = this.acitivity.get().getLayoutInflater()
.inflate(R.layout.favourite_episode_fragment_layout, null);
ListView list = (ListView) v.findViewById(R.id.listView1);
TextView empty_text = (TextView) v.findViewById(R.id.empty);
View loadingView = v.findViewById(R.id.loadingView);
switch (position) {
case FAVOURITE_EPISODE_INDEX:
list.setAdapter(getmFavouriteEpisodeAdapter());
empty_text.setText(Util.getApplicationContext().getString(
R.string.favourite_empty_episode));
empty_text.setTag(TAG_EMPTY_EPISODE);
loadingView.setTag(TAG_LOADING_EPISODE);
if (favouriteFragment.get().episodeInitialized.get()
&& getmFavouriteEpisodeAdapter().getCount() == 0) {
loadingView.setVisibility(View.GONE);
empty_text.setVisibility(View.VISIBLE);
}
break;
case FAVOURITE_SHOW_INDEX:
list.setAdapter(getmFavouriteShowAdapter());
empty_text.setText(Util.getApplicationContext().getString(
R.string.favourite_empty_show));
empty_text.setTag(TAG_EMPTY_SHOW);
loadingView.setTag(TAG_LOADING_SHOW);
if (favouriteFragment.get().showInitialized.get()
&& getmFavouriteShowAdapter().getCount() == 0) {
empty_text.setVisibility(View.VISIBLE);
loadingView.setVisibility(View.GONE);
}
break;
}
((ViewPager) container).addView(v, 0);
if (((ViewPager) container).getCurrentItem() == 0) {
favouriteFragment.get().loadEpisode();
}
return v;
}
#Override
public boolean isViewFromObject(View arg0, Object arg1) {
return arg0 == arg1;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((View) object);
}
public FavouriteEpisodeAdapter getmFavouriteEpisodeAdapter() {
return mFavouriteEpisodeAdapter;
}
public void setmFavouriteEpisodeAdapter(
FavouriteEpisodeAdapter mFavouriteEpisodeAdapter) {
this.mFavouriteEpisodeAdapter = mFavouriteEpisodeAdapter;
}
public FavouriteShowAdapter getmFavouriteShowAdapter() {
return mFavouriteShowAdapter;
}
public void setmFavouriteShowAdapter(
FavouriteShowAdapter mFavouriteShowAdapter) {
this.mFavouriteShowAdapter = mFavouriteShowAdapter;
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageSelected(int arg0) {
figureWhichToLoad(arg0);
}
private void figureWhichToLoad(int arg0) {
try {
switch (arg0) {
case 0:// episode
favouriteFragment.get().loadEpisode();
break;
case 1:// show
favouriteFragment.get().loadShow();
break;
}
} catch (Exception ex) {
ex.printStackTrace();
}
}
}