I have viewPager with 2 views. I need to get the second view by click and by flip. It works. But when I an in the second view I have to have button animation. This button is my customView. This animation doesn't work. And I don't know why. onPageSelected(int position) method works, because I get log.
my customView class:
public class CustomView extends LinearLayout {
private LayoutInflater mInflater;
private Button button;
private ViewPager viewPager;
private float buttonWidth;
public void setPager(ViewPager viewPager) {
this.viewPager = viewPager;
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
setClick();
}
#Override
public void onPageSelected(int position) {
ViewTreeObserver vto = button.getViewTreeObserver();
vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
#Override
public void onGlobalLayout() {
buttonWidth = button.getWidth();
}
});
DisplayMetrics metrics = new DisplayMetrics();
((Activity) getContext()).getWindowManager().getDefaultDisplay().getRealMetrics(metrics);
boolean isDisplayPortrait = getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT;
float middleScreen = isDisplayPortrait ? metrics.widthPixels / 2 : metrics.heightPixels / 2;
float movingDistanceForButton = middleScreen - buttonWidth / 2;
final TranslateAnimation animation = new TranslateAnimation(0, movingDistanceForButton, 0, 0);
animation.setDuration(3000);
animation.setFillAfter(true);
if (position == 1) {
button.setAnimation(animation);
Log.e("position1", "pos1");
} else {
button.getAnimation().cancel();
}
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public CustomView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
mInflater = LayoutInflater.from(context);
View v = mInflater.inflate(R.layout.custom_view, this, true);
button = v.findViewById(R.id.nextBotton);
}
public void setClick() {
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
}
});
}
and my activity class:
public class Activity extends AppCompatActivity {
private ViewPager viewPager;
private PagerAdapter customPagerAdapter;
private CustomView customView;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customPagerAdapter = new PagerAdapter(this);
viewPager = findViewById(R.id.viewPager);
customView = findViewById(R.id.myCustomView);
viewPager.setAdapter(customPagerAdapter);
customView.setPager(viewPager);
}
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 have ViewPager. Every ViewPager's page is customView. In custom view class in addOnPageChangeListener(new ViewPager.OnPageChangeListener() method I get null. I can't understand why, because in other method with viewPager - setOnClickListener(new OnClickListener() there are no null. This method works.
my custom view:
public class CustomView extends LinearLayout {
private LayoutInflater mInflater;
private Button button;
private ViewPager viewPager;
public void setPager(ViewPager viewPager) {
this.viewPager = viewPager;
}
public CustomView(#NonNull Context context) {
super(context);
}
public CustomView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
mInflater = LayoutInflater.from(context);
View v = mInflater.inflate(R.layout.custom_view, this, true);
button = v.findViewById(R.id.nextButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
}
});
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
and activity class:
public class Activity extends AppCompatActivity {
private ViewPager viewPager;
private CustomPagerAdapter customPagerAdapter;
private CustomView customView;
protected void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
customPagerAdapter = new CustomPagerAdapter(this);
viewPager = findViewById(R.id.viewPager);
customView = findViewById(R.id.customView);
viewPager.setAdapter(customPagerAdapter);
customView.setPager(viewPager);
}
}
and I get error:
E/AndroidRuntime: Caused by: java.lang.NullPointerException: Attempt to invoke virtual method 'void androidx.viewpager.widget.ViewPager.addOnPageChangeListener(androidx.viewpager.widget.ViewPager$OnPageChangeListener)' on a null object reference
at CustomView.<init>(line : viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener())
You are calling the addOnPageChangeListener in constructor of the CustomView, and the viewpager is not set in your view yet. Try to call addOnPageChangeListener in your setPager method.
public class CustomView extends LinearLayout {
private LayoutInflater mInflater;
private Button button;
private ViewPager viewPager;
public void setPager(ViewPager viewPager) {
this.viewPager = viewPager;
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
public CustomView(#NonNull Context context) {
super(context);
}
public CustomView(#NonNull Context context, #Nullable AttributeSet attrs) {
super(context, attrs);
mInflater = LayoutInflater.from(context);
View v = mInflater.inflate(R.layout.custom_view, this, true);
button = v.findViewById(R.id.nextButton);
button.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1, true);
}
});
}
I'm trying to replace colors by images from Drawable in this code.
I found this tutorial on how we can make an auto images slider by using viewpager on Android Studio, but this code is to switch colors images how can I replace this colors by images?
Here is my SliderAdapter.java
public class SliderAdapter extends PagerAdapter {
private Context context;
private List<Integer> color;
private List<String> colorName;
public SliderAdapter(Context context, List<Integer> color, List<String> colorName) {
this.context = context;
this.color = color;
this.colorName = colorName;
}
#Override
public int getCount() {
return color.size();
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = inflater.inflate(R.layout.item_slider, null);
TextView textView = (TextView) view.findViewById(R.id.textView);
LinearLayout linearLayout = (LinearLayout)
view.findViewById(R.id.linearLayout);
textView.setText(colorName.get(position));
linearLayout.setBackgroundColor(color.get(position));
ViewPager viewPager = (ViewPager) container;
viewPager.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager viewPager = (ViewPager) container;
View view = (View) object;
viewPager.removeView(view);
}
}
here is my MainActivity
public class MainActivity extends AppCompatActivity {
ViewPager viewPager;
TabLayout indicator;
List<Integer> color;
List<String> colorName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main_activity);
viewPager=(ViewPager)findViewById(R.layout.viewPager);
indicator=(TabLayout)findViewById(R.layout.indicator);
color = new ArrayList<>();
color.add(Color.RED);
color.add(Color.GREEN);
color.add(Color.BLUE);
colorName = new ArrayList<>();
colorName.add("RED");
colorName.add("GREEN");
colorName.add("BLUE");
viewPager.setAdapter(new SliderAdapterDemo(this, color, colorName));
indicator.setupWithViewPager(viewPager, true);
Timer timer = new Timer();
timer.scheduleAtFixedRate(new SliderTimer(), 4000, 6000);
}
private class SliderTimer extends TimerTask {
#Override
public void run() {
MainActivity.this.runOnUiThread(new Runnable() {
#Override
public void run() {
if (viewPager.getCurrentItem() < color.size() - 1) {
viewPager.setCurrentItem(viewPager.getCurrentItem() + 1);
} else {
viewPager.setCurrentItem(0);
}
}
});
}
}
}
I would like to know, I have a ViewPager inside a DialogFragment, and I would like to know, how would I dismiss my DialogFragment from a Fragment inside a ViewPager? Here is the code I have so far:
DialogFragment code:
public class ReportDialog extends DialogFragment {
public static ReportDialog newInstance() {
ReportDialog rd = new ReportDialog();
return rd;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(STYLE_NO_TITLE, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.report_dialog, container);
ViewPager viewPager = (ViewPager) view.findViewById(R.id.pager);
List<Fragment> fragments = getFragments();
ReportAdapter reportAdapter = new ReportAdapter(getChildFragmentManager(), fragments);
viewPager.setAdapter(reportAdapter);
getDialog().getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return view;
}
private List<Fragment> getFragments(){
List<Fragment> fList = new ArrayList<Fragment>();
fList.add(MainReport.newInstance());
//to add another fragment soon
return fList;
}
}
ViewPager code:
public class CustomPager extends ViewPager {
private View mCurrentView;
public CustomPager(Context context) {
super(context);
}
public CustomPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
if (mCurrentView == null) {
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
return;
}
int height = 0;
mCurrentView.measure(widthMeasureSpec, MeasureSpec.makeMeasureSpec(0, MeasureSpec.UNSPECIFIED));
int h = mCurrentView.getMeasuredHeight();
if (h > height) height = h;
heightMeasureSpec = MeasureSpec.makeMeasureSpec(height, MeasureSpec.EXACTLY);
super.onMeasure(widthMeasureSpec, heightMeasureSpec);
}
public void measureCurrentView(View currentView) {
mCurrentView = currentView;
requestLayout();
}
public int measureFragment(View view) {
if (view == null) {
return 0;
}
view.measure(0, 0);
return view.getMeasuredHeight();
}
}
MainReport code:
public class MainReport extends Fragment {
public View reportView;
public static final MainReport newInstance() {
MainReport mr = new MainReport();
return mr;
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
final View pageView = inflater.inflate(R.layout.activity_report, null);
ImageButton ib;
ib = (ImageButton) pageView.findViewById(R.id.done);
ib.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
//need to dismiss DialogFragment here
}
});
ib = (ImageButton) pageView.findViewById(R.id.export);
ib.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
ib = (ImageButton) pageView.findViewById(R.id.ptview);
ib.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
}
});
return pageView;
}
}
EDIT - Code to show DialogFragment:
//Located in main activity class
void showReportDialog() {
DialogFragment reportDialog = ReportDialog.newInstance();
reportDialog.show(getFragmentManager(), "report_dialog");
}
How would I dismiss the DialogFragment from the Fragment inside the ViewPager?
In your onClick add following
Intent intent = new Intent(BROADCAST_ACTION);
LocalBroadcastManager.getInstance(context).sendBroadcast(intent);
In your dialogFragment add following
public static final String BROADCAST_ACTION = "BROADCAST_ACTION";
BroadcastReceiver broadcastReceiver = new BroadcastReceiver() {
#Override
public void onReceive(Context context, Intent intent) {
if (intent.getAction() != null &&
intent.getAction().equals(BROADCAST_ACTION)) {getDialog.dismiss();
}
}
};
#Override
protected void onResume() {
super.onResume();
LocalBroadcastManager.getInstance(
MainActivity.this).registerReceiver(broadcastReceiver, new IntentFilter(BROADCAST_ACTION));
}
#Override
protected void onPause() {
super.onPause();
LocalBroadcastManager.getInstance(MainActivity.this).unregisterReceiver(broadcastReceiver);
}
You could probably do something like this:
void showReportDialog() {
Fragment Transaction ft = getFragmentManager().beginTransaction();
ft.addToBackStack("report_dialog");
DialogFragment reportDialog = ReportDialog.newInstance();
reportDialog.show(ft, "report_dialog");
}
And then inside of MainReport:
getFragmentManager().popBackStack("report_dialog", FragmentManager.POP_BACK_STACK_INCLUSIVE);
I have implemented a ViewPager in my application which consist of two slides. I can go from first slide to second slide and reverse as well. But I have a special case here. If the user goes from First Slide to Second Slide. He should not be able to go back to the First slide. I need to disable going back to the First Slide once he enters the Second Slide.
Here is my code:
public class BotConnectionDialog extends DialogFragment {
private RelativeLayout toolbar;
private ImageView toolbarCloseButton;
private View layoutView;
private ViewPager viewPager;
private BotConnectionDialogAdapter myViewPagerAdapter;
private LinearLayout dotsLayout;
private TextView[] dots;
int width, height;
DisplayMetrics metrics;
private int[] layouts;
private final String TAG = BotConnectionDialog.class.getSimpleName();
private Button btnSkip, btnNext;
View.OnClickListener myListener = new View.OnClickListener() {
#Override
public void onClick(View view) {
Handler handler = new Handler();
handler.post(new Runnable() {
#Override
public void run() {
getActivity().getSupportFragmentManager().popBackStackImmediate();
}
});
}
};
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setStyle(DialogFragment.STYLE_NORMAL, android.R.style.Theme_Black_NoTitleBar_Fullscreen);
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.botconnection_layout, container, false);
Typeface typeface = Typeface.createFromAsset(getActivity().getAssets(), "fonts/corbert.otf");
toolbar = (RelativeLayout) rootView.findViewById(R.id.customAppBarLayout);
toolbar.setBackgroundColor(Color.parseColor("#00000000"));
toolbarCloseButton = (ImageView) rootView.findViewById(R.id.toolbarCloseButton);
toolbarCloseButton.setOnClickListener(myListener);
viewPager = (ViewPager) rootView.findViewById(R.id.view_pager);
dotsLayout = (LinearLayout) rootView.findViewById(R.id.layoutDots);
btnSkip = (Button) rootView.findViewById(R.id.btn_skip);
btnSkip.setTypeface(typeface);
btnNext = (Button) rootView.findViewById(R.id.btn_next);
btnNext.setTypeface(typeface);
metrics = getResources().getDisplayMetrics();
width = metrics.widthPixels;
height = metrics.heightPixels;
// layouts of all welcome sliders
// add few more layouts if you want
layouts = new int[]{
R.layout.slide1,
R.layout.slide2};
// adding bottom dots
addBottomDots(0);
myViewPagerAdapter = new BotConnectionDialogAdapter();
viewPager.setAdapter(myViewPagerAdapter);
viewPager.addOnPageChangeListener(viewPagerPageChangeListener);
btnNext.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
// checking for last page
// if last page home screen will be launched
int current = getItem(+1);
if (current < layouts.length) {
// move to next screen
viewPager.setCurrentItem(current);
} else {
}
}
});
return rootView;
}
private void addBottomDots(int currentPage) {
dots = new TextView[layouts.length];
int[] colorsActive = getResources().getIntArray(R.array.array_dot_active);
int[] colorsInactive = getResources().getIntArray(R.array.array_dot_inactive);
dotsLayout.removeAllViews();
for (int i = 0; i < dots.length; i++) {
dots[i] = new TextView(getActivity());
dots[i].setText(Html.fromHtml("•"));
dots[i].setTextSize(35);
dots[i].setTextColor(colorsInactive[currentPage]);
dotsLayout.addView(dots[i]);
}
if (dots.length > 0)
dots[currentPage].setTextColor(colorsActive[currentPage]);
}
private int getItem(int i) {
return viewPager.getCurrentItem() + i;
}
// viewpager change listener
ViewPager.OnPageChangeListener viewPagerPageChangeListener = new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
addBottomDots(position);
// changing the next button text 'NEXT' / 'GOT IT'
if (position == layouts.length - 1) {
// last page. make button text to GOT IT
btnNext.setText(getString(R.string.start));
btnSkip.setVisibility(View.GONE);
/**
* bluetooth connection the bot
*/
Toast.makeText(getActivity(), "Finished", Toast.LENGTH_SHORT).show();
} else {
// still pages are left
btnNext.setText(getString(R.string.next));
btnSkip.setVisibility(View.VISIBLE);
/**
* First page
*/
Toast.makeText(getActivity(), "2nd page", Toast.LENGTH_SHORT).show();
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int arg0) {
}
};
#NonNull
#Override
public Dialog onCreateDialog(Bundle savedInstanceState) {
Dialog dialog = super.onCreateDialog(savedInstanceState);
//dialog.getWindow().setBackgroundDrawable(new ColorDrawable(android.graphics.Color.TRANSPARENT));
dialog.getWindow().requestFeature(Window.FEATURE_NO_TITLE);
return dialog;
}
#Override
public void onResume() {
super.onResume();
// getDialog().getWindow().setLayout((7 * width) / 7, (4 * height) / 5);
}
public class BotConnectionDialogAdapter extends PagerAdapter {
/**
* View pager adapter
*/
private LayoutInflater layoutInflater;
public BotConnectionDialogAdapter() {
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) getActivity().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(layouts[position], container, false);
container.addView(view);
return view;
}
#Override
public int getCount() {
return layouts.length;
}
#Override
public boolean isViewFromObject(View view, Object obj) {
return view == obj;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
View view = (View) object;
container.removeView(view);
}
}
}
/**
* To disable and enable scrolling on ViewPager, just set shouldScroll to true or false.
*/
public class ScrollableViewPager extends ViewPager {
private boolean shouldScroll = true;
public ScrollableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
public void setShouldScroll(boolean shouldScroll) {
this.shouldScroll = shouldScroll;
}
#Override
public boolean onTouchEvent(MotionEvent ev) {
return shouldScroll && super.onTouchEvent(ev);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent ev) {
return shouldScroll && super.onInterceptTouchEvent(ev);
}
}
Now use this ScrollableViewPager in place of the default ViewPager and in your onPageSelected() callback
check for the position. If it is the last position, call the setShouldScroll(false) method on your viewPager instance, which will make shouldScroll to false in our ScrollableViewPager class and eventually make the scrolling invalid as we have overridden onTouchEvent() and onInterceptTouchEvent() method, which checks for the value of shouldScroll.