how to slide images automatically along by sliding custom by fingers - android

I have implemented an image slider with dots. Working perfectly. Slider is working only on manual by sliding from finger left or right not automatically by a time interval 3 seconds.
See the code and suggest me some approach to working slider automatically.
ViewPager in .xml layout file
<androidx.viewpager.widget.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="160dp"
android:layout_alignParentTop="true" />
<LinearLayout
android:paddingTop="8dp"
android:id="#+id/slider_dots"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:gravity="center_horizontal|center_vertical"
android:layout_below="#id/view_pager"></LinearLayout>
</RelativeLayout>
And here's ViewPageAdapter java class
public class ViewPagerAdapter extends PagerAdapter {
Context context;
LayoutInflater layoutInflater;
int images[] = {R.mipmap.banner, R.mipmap.banner1, R.mipmap.banner2, R.mipmap.banner3, R.mipmap.banner4, R.mipmap.banner5};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return images.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater) context.getSystemService(LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.slider_banner_layout, null);
ImageView imageView = view.findViewById(R.id.image_view_banner_image);
imageView.setImageResource(images[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);
}
}
MainActivity.java
public class HomeActivity extends AppCompatActivity {
ViewPager viewPager;
LinearLayout sliderDotsPanel;
ImageView[] dots;
private int dotCount;
ViewPagerAdapter viewPagerAdapter;
private Toolbar toolbar;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home);
toolbar = findViewById(R.id.app_bar);
toolbar.setTitle("");
toolbar.setLogo(R.mipmap.toolbar_logo);
setSupportActionBar(toolbar);
viewPager = findViewById(R.id.view_pager);
viewPagerAdapter= new ViewPagerAdapter(this);
viewPager.setAdapter(viewPagerAdapter);
sliderDotsPanel=findViewById(R.id.slider_dots);
initializeDots();
}
private void initializeDots() {
dotCount = viewPagerAdapter.getCount();
dots = new ImageView[dotCount];
for (int i = 0; i < dotCount; i++) {
dots[i] = new ImageView(this);
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotsPanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotCount; i++) {
dots[i].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.non_active_dot));
}
dots[position].setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
}
}

I will show you how to make it slide, one page after the other and then stop:
private void slideAutomatically(final long milliSeconds){
new Thread(new Runnable(){
#Override
public void run(){
for(int i = 0 ; i<6 ; i++){
//sleep
try{
Thread.sleep(milliSeconds);
}catch(InterruptedException e){
}
//change position
runOnUiThread(new Runnable(){
#Override
public void run(){
viewPager.setCurrentItem(i);}
});
}
}
}).start();
}
Call this method whenever you want the pages to slide automatically:
//lets say I want the pages to change every 3 seconds
slideAutomatically(3000);

Related

Auto slider images using ViewPager

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

ViewPager with the dots only beginning on the third slide (3/3)

I've a ViewPager, with dots, and it's only beginning on the third slide [3/3].
But sometimes, the second slide is not showed in the ViewPager. I tried to use the Log, to show the initial position and the current position, when the position changes, and the result was: the second option is not showed, only the first and the third.
The resume of the hierarchy of my class is:
HelpHomeFragment extends BaseFragment {
ViewPagerAdapter extends PagerAdapter {}
HelpFrag1 extends Fragment {}
HelpFrag2 extends Fragment {}
HelpFrag3 extends Fragment {}
}
and my code is below:
HelpHomeFragment.java
public class HelpHomeFragment extends BaseFragment {
#BindView(R.id.llt_help_tipsbase)
LinearLayout llTips;
#BindView(R.id.vpg_help)
ViewPager viewPager;
#BindView(R.id.slider_dots)
LinearLayout sliderDotspanel;
private int dotscount;
private ImageView[] dots;
private static final String ARG_PARAM1 = "Title";
private DataManager dm;
private HelpHomeFragmentPresenter<HelpHomeFragment> presenter;
private ListHelpsAdapter listHelpsAdapter;
private MyTimerTask mtt;
public static Fragment newInstance(String title) {
Bundle args = new Bundle();
args.putString(ARG_PARAM1, title);
Fragment fragment = new HelpHomeFragment();
fragment.setArguments(args);
return fragment;
}
#Override
public void onCreate(#Nullable Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
dm = ((MvpApp) getActivity().getApplication()).getDataManager();
presenter = new HelpHomeFragmentPresenter<>(dm);
presenter.onAttach(this);
}
#Override
public void onResume() {
super.onResume();
showSlideshowTips();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_help_home, container, false);
ButterKnife.bind(this, view);
return view;
}
#Override
public void showSlideshowTips() {
configSlideshow();
}
#Override
public void configSlideshow() {
ViewPagerAdapter viewPagerAdapter = new ViewPagerAdapter(getContext());
viewPager.setAdapter(viewPagerAdapter);
dotscount = viewPagerAdapter.getCount();
dots = new ImageView[dotscount];
for (int i = 0; i < dotscount; i++) {
dots[i] = new ImageView(getContext());
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(8, 0, 8, 0);
sliderDotspanel.addView(dots[i], params);
}
dots[0].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageScrolled(int position, float positionOffset, int positionOffsetPixels) {
}
#Override
public void onPageSelected(int position) {
for (int i = 0; i < dotscount; i++)
dots[i].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.nonactive_dot));
dots[position].setImageDrawable(ContextCompat.getDrawable(getBaseActivity(), R.drawable.active_dot));
}
#Override
public void onPageScrollStateChanged(int state) {
}
});
try {
mtt = new MyTimerTask();
new Timer().scheduleAtFixedRate(mtt, 4500, 9000);
} catch (Exception e) {
e.printStackTrace();
}
}
// CUSTOM TIMER
class MyTimerTask extends TimerTask {
#Override
public void run() {
try {
getBaseActivity().runOnUiThread(() -> {
if (viewPager.getCurrentItem() == 0) {
viewPager.setCurrentItem(1);
} else if (viewPager.getCurrentItem() == 1) {
viewPager.setCurrentItem(2);
} else {
viewPager.setCurrentItem(0);
}
});
} catch (Exception e) {
e.printStackTrace();
}
}
}
// CUSTOM PAGE ADAPTER
class ViewPagerAdapter extends PagerAdapter {
private Context context;
private LayoutInflater layoutInflater;
Fragment[] fragments = {new HelpFrag1(), new HelpFrag2(), new HelpFrag3()};
public ViewPagerAdapter(Context context) {
this.context = context;
}
#Override
public int getCount() {
return fragments.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View view = null;
if (layoutInflater != null) {
view = layoutInflater.inflate(R.layout.custom_layout, null);
try {
View finalView = view;
getActivity().runOnUiThread(() -> getActivity().getSupportFragmentManager().beginTransaction()
.replace(finalView.getId(), fragments[position], "findThisFragment")
.addToBackStack(null).commit());
} catch (Exception e){
e.printStackTrace();
}
}
ViewPager vp = (ViewPager) container;
vp.addView(view, 0);
return view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
ViewPager vp = (ViewPager) container;
View view = (View) object;
vp.removeView(view);
}
}
// classes fragment for the slideshow. Each fragment is an slide
public static class HelpFrag1 extends Fragment {
public HelpFrag1() {
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
return inflater.inflate(R.layout.fragment_help_frag1, container, false);
}
}
// and more two classes HelpFrag, only changing the end (HelpFrag2 and HelpFrag3)
// and changing the layout to fragment_help_frag2 and fragment_help_frag3
}
and my layout base of the ViewPager is:
fragment_help_home.xml
<!-- another tag -->
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<android.support.v4.view.ViewPager
android:id="#+id/vpg_help"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="30dp"
android:paddingTop="4dp"
android:layout_marginRight="30dp"
android:overScrollMode="never" />
<LinearLayout
android:id="#+id/slider_dots"
android:layout_width="100dp"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:layout_marginLeft="20dp"
android:layout_marginRight="20dp"
android:layout_marginTop="-20dp"
android:gravity="center_vertical|center_horizontal"
android:orientation="horizontal" />
</LinearLayout>
<!-- another tag -->

How to avoid going to previous slide in Viewpager in android

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.

How to display video in VideoView in the center of the screen?

I am creating ViewPager with two VideoViews. On sliding pages, video on current page start playing. One problem: how to display video in VideoView in the center of the screen ?
Here is my code,
MainActivity.java:
public class MainActivity extends Activity{
private class MyViewPagerAdapter extends PagerAdapter implements ViewPager.OnPageChangeListener
{
private Vector<View> pages;
private ViewGroup myContainer;
private int currentPageId;
private boolean flag;
public MyViewPagerAdapter(Context context, Vector<View> pages)
{
this.pages=pages;
}
#Override
public int getCount()
{
return pages.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position)
{
flag = true;
currentPageId = 0;
int positionNow = myPager.getCurrentItem();
View page = pages.get(position);
container.addView(page);
myContainer = container;
if(positionNow == position)
StartVideo(container, positionNow);
return page;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object)
{
container.removeView((View) object);
myContainer = container;
}
#Override
public boolean isViewFromObject(View view, Object object)
{
return view.equals(object);
}
#Override
public void onPageScrollStateChanged(int arg0)
{
if(flag)
{
MyVideoView currVideo = (MyVideoView) myContainer.getChildAt(currentPageId+1);
if(currVideo != null)
if(currVideo.getVideoPath() != null)
currVideo.pause();
}
else
flag = !flag;
}
#Override
public void onPageSelected(int arg0)
{
flag = false;
currentPageId = myPager.getCurrentItem();
StartVideo(myContainer, myPager.getCurrentItem());
}
private void StartVideo(ViewGroup container, int position)
{
View page = container.getChildAt(position+1);
MyVideoView curVideo = (MyVideoView) page;
Log.d("Andrew", curVideo.getVideoPath());
curVideo.start();
}
}
private ViewPager myPager;
private MyViewPagerAdapter myAdapter;
private Vector<View> pages;
private MyVideoView myVideoView;
int currentPage, previousPage;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
pages = new Vector<View>();
for(int i=1; i <= 2; i++)
{
myVideoView = new MyVideoView(this);
myVideoView.setVideoPath("videoPath");
pages.add(myVideoView);
}
this.myAdapter = new MyViewPagerAdapter(this, pages);
this.myPager = (ViewPager) this.findViewById(R.id.viewpageronecard);
this.myPager.setAdapter(myAdapter);
myPager.setOnPageChangeListener(myAdapter);
myPager.setOffscreenPageLimit(1);
myPager.setCurrentItem(0);
}
}
activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity" >
<android.support.v4.view.ViewPager
android:id="#+id/viewpageronecard"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerInParent="true"
android:layout_centerHorizontal="true"
android:layout_centerVertical="true"
android:background="#222222" >
</android.support.v4.view.ViewPager>
</RelativeLayout>
Although it is an old question, perhaps someone else is struggling with it, too, as I had the same problem. I solved it by changing
android:layout_centerInParent="true"
android:layout_centerVertical="true"
android:layout_centerHorizontal="true"
to
android:layout_gravity="center"
in the xml for the VideoView I used to populate the ViewPager.

Have misunderstanding with PagerAdapter for ViewPager. InstantianteItem method never gets called

Here is my simple PagerAdapter and onCreate() of activity for paging.
public class MPagerAdapter extends PagerAdapter{
List<ViewGroup> pages = null;
public MPagerAdapter(List<ViewGroup> pages){
this.pages = pages;
}
#Override
public Object instantiateItem(ViewGroup collection, int position){
ViewGroup v = pages.get(position);
((ViewPager) collection).addView(v, 0);
return v;
}
#Override
public void destroyItem(ViewGroup collection, int position, Object view){
((ViewPager) collection).removeView((View) view);
}
#Override
public int getCount(){
return pages.size();
}
#Override
public boolean isViewFromObject(View view, Object object){
return view.equals(object);
}
#Override
public void finishUpdate(View arg0){
}
#Override
public void restoreState(Parcelable arg0, ClassLoader arg1){
}
#Override
public Parcelable saveState(){
return null;
}
#Override
public void startUpdate(View arg0){
}
}
and here is onCreate() of activity in which pager will live.
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_pager);
getActionBar().setDisplayHomeAsUpEnabled(true);
Intent intent = getIntent();
String message = intent.getStringExtra(MainActivity.EXTRA_MESSAGE);
amount=Integer.parseInt(message);
Resources res = getResources();
Drawable background = res.getDrawable(R.drawable.page_back1);
BackgroudImage bImage = new BackgroudImage(x, y, background);
List<MyLayout> pages = new ArrayList<MyLayout>();
int a = amount/bImage.mPointsList.size();
for (int i=0; i<=a; i++){
MyLayout page = new MyLayout(getBaseContext(), bImage);
page.setLayoutParams(new ViewGroup.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT));
pages.add(page);
}
MPagerAdapter pagerAdapter = new MPagerAdapter(pages);
ViewPager viewPager = (ViewPager)findViewById(R.id.pager);//new ViewPager(this);
viewPager.setAdapter(pagerAdapter);
viewPager.setCurrentItem(1);
}
OnLayout() method of my custom layout which is used as a control for pages of pagerView
protected void onLayout(boolean changed, int l, int t, int r, int b) {
if (PagerActivity.amount<=points.size()) {
for (int i=0; i<PagerActivity.amount; i++){
ImageView childV = new ImageView(super.getContext());
childV.setBackgroundResource(R.drawable.lesson_frame_closed);
ViewGroup.LayoutParams imageParams = new ViewGroup.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
childV.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
}
});
this.addView(childV, imageParams);
}
PagerActivity.amount=0;
}
if ((float)(bgrImage.getBackground().getIntrinsicWidth())/(float)(bgrImage.getBackground().getIntrinsicHeight())<(float)this.getMeasuredWidth()/(float)this.getMeasuredHeight()) {
scaleFX=(float)this.getMeasuredHeight()/(float)bgrImage.getBackground().getIntrinsicWidth();
scaleFY=(float)this.getMeasuredHeight()/(float)bgrImage.getBackground().getIntrinsicHeight();
} else {
scaleFX=(float)this.getMeasuredWidth()/(float)bgrImage.getBackground().getIntrinsicWidth();
scaleFY=(float)this.getMeasuredWidth()/(float)bgrImage.getBackground().getIntrinsicHeight();
}
for (int i = 0; i < getChildCount(); i++) {
final View childV = getChildAt(i);
if (childV.getVisibility() != View.VISIBLE)
continue;
childV.layout((int)(points.get(i).getOriginX()*scaleFX), (int)(points.get(i).getOriginY()*scaleFY), childV.getWidth(), childV.getHeight());
}
}
Can't understand why InstantiateItem() isn't being called. Any helpful idea will be appreciated.
The ViewPager is a View and should be added to the UI. typically by declaring it in a layout file.
Extracted from the SDK samples :
the layout file :
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:gravity="center_horizontal"
android:orientation="vertical"
android:padding="4dip" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="match_parent"
android:layout_height="0px"
android:layout_weight="1" >
</android.support.v4.view.ViewPager>
...
the activity class
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.fragment_pager);
mAdapter = new MyAdapter(getSupportFragmentManager());
mPager = (ViewPager)findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
...
The complete sources are in the extras/android/support/samples/Support4Demos directory of the SDK

Categories

Resources