ViewPager2 fragment click event - android

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

Related

Fragment animation issue

Working on simple animation in fragments. I have three fragments where I have to animate the views inside the fragment but the problem I am facing right now is that the animation is not working in the second fragment and when I revisit the fragment then also the animation is not working.
Adapter class
public class MyPageAdapter extends FragmentPagerAdapter {
private final int NUM_ITEMS = 3;
Context mContext;
public MyPageAdapter(FragmentManager fm, Context mContext) {
super(fm);
this.mContext = mContext;
}
public int getCount() {
return NUM_ITEMS;
}
public Fragment getItem(int position) {
// MainActivity.updatedposition(position);
if (position == 0)
return SliderOne.newInstance();
else if (position == 1)
return SliderTwo.newInstance();
else if (position == 2)
return SliderThree.newInstance();
return null;
}
}
Slider Activity
pager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {
}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
public void onPageSelected(int position) {
if (position == 0) {
SliderOne fragment = new SliderOne();
fragment.initAnimation(mContext);
}
else if (position == 1) {
SliderTwo fragment = new SliderTwo();
fragment.initAnimation(mContext);
}
if (position == 2) {
SliderThree fragment = new SliderThree();
fragment.initAnimation(mContext);
}
// Check if this is the page you want.
}
});
Fragment class
public class SliderThree extends Fragment implements PageSelectedAnimation {
ImageView logo;
TextView tv_appname;
CustomTextView tv_msg_2;
Animation smalltobig, nothingtocome, btnanim;
Context mContext;
public static SliderThree newInstance() {
SliderThree fragment = new SliderThree();
return fragment;
}
public SliderThree() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View root = inflater.inflate(R.layout.slider_three, null);
mContext = getActivity();
logo = root.findViewById(R.id.logo);
tv_appname = root.findViewById(R.id.tv_appname);
tv_msg_2 = root.findViewById(R.id.tv_msg_2);
tv_msg_2.setText(Html.fromHtml("Message other users to negotiate<br><p>the perfect trade or deal.Always</p><p>use your best judgement when</p><p>buying or selling.</p>"));
return root;
}
#Override
public void onResume() {
super.onResume();
}
#Override
public void initAnimation(Context mContext) {
smalltobig = AnimationUtils.loadAnimation(mContext, R.anim.smalltobig);
nothingtocome = AnimationUtils.loadAnimation(mContext, R.anim.nothingtocome);
btnanim = AnimationUtils.loadAnimation(mContext, R.anim.nothingtocome);
logo.setAnimation(smalltobig);
logo.setAnimation(nothingtocome);
tv_appname.setAnimation(btnanim);
}
}
interface created
public interface PageSelectedAnimation {
void initAnimation(Context context);
}
Error :-
java.lang.NullPointerException: Attempt to invoke virtual method 'android.view.View android.view.View.findViewById(int)' on a null object reference
at com.xxx.slider.SliderThree.initAnimation(SliderThree.java:79)
at com.xxx.activities.SliderActivity$2.onPageSelected(SliderActivity.java:103)
Sharing my code:
Fragment Code
I assume from the tags you are using that you are including those Fragments on a ViewPager.
ViewPager charges the current and the adjacents, so they are ready when needed. Therefore you animation runs out of the screen when it is charged.
I would suggest to use ViewPager.onPageChangeListener:
viewPager.addOnPageChangeListener(new OnPageChangeListener() {
public void onPageScrollStateChanged(int state) {}
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {}
public void onPageSelected(int position) {
// Check if this is the page you want.
}
});
and run the animation method from there.
EDIT:
You can do that nicely creating and implementing an interface on every Fragment.
interface PageSelectedAnimation{
fun initAnimation()
}
.
public class SliderThree extends Fragment implements PageSelectedAnimation
and finally:
public void onPageSelected(int position) {
((PageSelectedAnimation)getYourFragment(position)).initAnimation()
}

After viewpager adapter notifyDataSetChanged,pagetransformer not work

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.

Add/ remove method working in onCreate but not in onPageSelected

i have two viewpager i am removing current page of one viewpager from second pager. and add removed page again when swipe to next position. same process for second viewpager. Problem is add and remove method work fine if i use them in onCreate but not working in onPageSelected. and other problem is if i add any removed page on same position again it show me added page on current position of viewpager. i want page just add on that specific position but do not set on current position.
Below is my code.Any help will be appreciated.
public class MainActivity extends FragmentActivity {
CustomViewPager pager1,pager2;
List<Fragment> fragments1,fragments2;
public PagerAdapter adapter1;
public PagerAdapter1 adapter2;
int lostPositionRight;
int lostPositionLeft;
ArrayList<String> image = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
ArrayList<String> imageNew = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
ArrayList<Integer> images = new ArrayList<Integer>() {{
add(R.drawable.first);
add(R.drawable.second);
add(R.drawable.three);
add(R.drawable.four);
add(R.drawable.xiaomi);
}};
ArrayList<Integer> imagesNew = new ArrayList<Integer>() {{
add(R.drawable.first);
add(R.drawable.second);
add(R.drawable.three);
add(R.drawable.four);
add(R.drawable.xiaomi);
}};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.text);
pager1 = (CustomViewPager) findViewById(R.id.pager1);
fragments1 = getFragments1();
adapter1 = new PagerAdapter(getSupportFragmentManager(), fragments1);
pager1.setAdapter(adapter1);
removeView1(1);
lostPositionLeft = 1;
adapter1.notifyDataSetChanged();
pager2 = (CustomViewPager) findViewById(R.id.pager2);
fragments2 = getFragments2();
adapter2 = new PagerAdapter1(getSupportFragmentManager(), fragments2);
pager2.setAdapter(adapter2);
pager2.setCurrentItem(1);
removeView2(0);
lostPositionRight = 0;
pager1.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
MyImageSlider fragmntDta = (MyImageSlider)findFragmentByPosition(pager1.getCurrentItem());
String value = fragmntDta.getTextOnTextView();
int p = Integer.parseInt(value);
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +p, Toast.LENGTH_SHORT);
toast.show();
addView2(lostPositionRight,lostPositionRight);
removeView2(p);
adapter2.notifyDataSetChanged();
lostPositionRight = p;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
pager2.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
MyImageSlider1 fragmntDta = (MyImageSlider1)findFragmentByPosition2(pager2.getCurrentItem());
String value1 = fragmntDta.getTextView();
Toast toast = Toast.makeText(getApplicationContext(),"Text is " +value1, Toast.LENGTH_SHORT);
toast.show();
int p = Integer.parseInt(value1);
addView1(lostPositionLeft,lostPositionLeft);
removeView1(p);
lostPositionLeft = p;
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public void addView1(int index,int position)
{
adapter1.addView1 (index,position);
adapter1.notifyDataSetChanged();
}
public void addView2(int index,int position)
{
adapter2.addView2 (index,position);
adapter2.notifyDataSetChanged();
}
public void removeView1 (int position)
{
adapter1.removeView1(pager1, position);
adapter1.notifyDataSetChanged();
}
public void removeView2 (int position)
{
adapter2.removeView2(pager2, position);
adapter2.notifyDataSetChanged();
}
public class PagerAdapter extends FragmentStatePagerAdapter {
private List<Fragment> fragments;
public PagerAdapter(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();
}
#Override
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
public int removeView1 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragments.remove (position);
pager.setAdapter (this);
notifyDataSetChanged();
return position;
}
public void addView1 (int index,int position)
{
fragments.add(index,MyImageSlider.newInstance(images.get(position),image.get(position)));
notifyDataSetChanged();
}
}
private List<Fragment> getFragments1() {
List<Fragment> fList = new ArrayList<>();
for (int i = 0; i < images.size(); i++) {
fList.add(MyImageSlider.newInstance(images.get(i),image.get(i)));
}
return fList;
}
public static class MyImageSlider extends Fragment {
int imageid;
String newid;
TextView textView;
public static MyImageSlider newInstance(int id,String s)
{
MyImageSlider slider=new MyImageSlider();
Bundle b=new Bundle();
b.putInt("imageid", id);
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextOnTextView(){
return (String) textView.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageid=getArguments().getInt("imageid");
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.leftpager,container, false);
ImageView iv=(ImageView)view.findViewById(R.id.image1);
textView = (TextView)view.findViewById(R.id.text);
iv.setImageResource(imageid);
textView.setText(newid);
return view;
}
}
public Fragment findFragmentByPosition(int position) {
PagerAdapter fragmentPagerAdapter = adapter1;
return getSupportFragmentManager().findFragmentByTag("android:switcher:" + pager1.getId() + ":" +
fragmentPagerAdapter.getItemId(position));
}
public class PagerAdapter1 extends FragmentStatePagerAdapter {
private List<Fragment> fragment;
public PagerAdapter1(FragmentManager fm, List<Fragment> fragments) {
super(fm);
this.fragment = fragments;
}
#Override
public Fragment getItem(int position) {
return this.fragment.get(position);
}
#Override
public int getCount() {
return this.fragment.size();
}
#Override
public int getItemPosition (Object object)
{
return POSITION_NONE;
}
public int removeView2 (ViewPager pager, int position)
{
pager.setAdapter (null);
fragment.remove (position);
pager.setAdapter (this);
notifyDataSetChanged();
return position;
}
public void addView2 (int index,int position)
{
fragment.add(index,MyImageSlider1.newInstance(imagesNew.get(position),imageNew.get(position)));
notifyDataSetChanged();
}
}
private List<Fragment> getFragments2() {
List<Fragment> fList = new ArrayList<Fragment>();
for (int i = 0; i < imagesNew.size(); i++) {
fList.add(MyImageSlider1.newInstance(imagesNew.get(i),imageNew.get(i)));
}
return fList;
}
public static class MyImageSlider1 extends Fragment {
int imageid;
String newid;
public TextView textView1;
public static MyImageSlider1 newInstance(int id,String s)
{
MyImageSlider1 slider=new MyImageSlider1();
Bundle b=new Bundle();
b.putInt("imageid", id);
b.putString("newid", s);
slider.setArguments(b);
return slider;
}
public String getTextView(){
return (String) textView1.getText();
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
imageid=getArguments().getInt("imageid");
newid = getArguments().getString("newid");
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.rightpager, container, false);
ImageView iv=(ImageView)view.findViewById(R.id.image2);
iv.setImageResource(imageid);
textView1 = (TextView)view.findViewById(R.id.text2);
textView1.setText(newid);
return view;
}
}
public Fragment findFragmentByPosition2(int position) {
PagerAdapter1 fragmentPagerAdapter2 = adapter2;
return getSupportFragmentManager().findFragmentByTag
("android:switcher:" + pager2.getId() + ":" + fragmentPagerAdapter2.getItemId(position));
}
}
First of all use FragmentStatePagerAdapter instead FragmentPagerAdapter.
But, for your desired purpose, you are going the wrong way.
Try doing this:
You said both view pagers are showing same thing. So there is no need too have two same list. One from each is enough.
ArrayList<String> imageNew = new ArrayList<String>() {{
add("0");
add("1");
add("2");
add("3");
add("4");
}};
ArrayList<Integer> images = new ArrayList<Integer>() {{
add(R.drawable.first);
add(R.drawable.second);
add(R.drawable.three);
add(R.drawable.four);
add(R.drawable.xiaomi);
}};
Define an onPageChangedListener for your view pager. So every time the page changed, you have the index. Just make a clone from both your lists and remove the desired index and make a new adapter and set that for the other view pager.

Recycler View - Custom Checkbox: keeping state while scrolling

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

ViewPager content not able to reset after page scrolled

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

Categories

Resources