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
Related
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);
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 -->
I created a "Slide Image" in first activity; which has five images. After I slide the last image(fifth), it should go to next activity,say-activity_next.xml.
Below is my code to slide Image i.e., SlideActivity.java
public class SlideActivity extends Activity {
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four,
R.drawable.five
};
#Override
public int getCount() {
return mImages.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Illustrations.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
}
}
I'm not getting where to pass Intent for next activity i.e., activity_next.xml
**** UPDATED CODE as per your suggestions ****
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.addOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
// TODO Auto-generated method stub
if(position==viewPager.getAdapter().getCount()){
Intent reg = new Intent(SlideActivity.this,activity_next.class);
startActivity(reg);
}
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
});
}
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four,
R.drawable.five
};
#Override
public int getCount() {
return mImages.length+1;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Illustrations.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
if(position < getCount()-1)
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
}
}
****activity_next.java code is below ****
public class activity_next extends Activity{
#Override
public void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_next);
}
}
**** activity_next.xml code is as below****
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" >
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Welcome to Nowhere Else" />
</LinearLayout>
I'm not getting where to pass Intent for next activity i.e.,
activity_next.xml
To start Activity on reach of last item in ViewPager add OnPageChangeListener to ViewPager and in onPageSelected start next Activity:
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
if(position==viewPager.getAdapter().getCount()){
//start next Activity here with activity_next.xml layout
}
}
....
});
If you want to slide the last image to go to the next Activity, like a "dismiss" efect, you should try something like this:
private class ImagePagerAdapter extends PagerAdapter {
private int[] mImages = new int[] {
R.drawable.one,
R.drawable.two,
R.drawable.three,
R.drawable.four,
R.drawable.five
};
#Override
public int getCount() {
return mImages.length+1;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = Illustrations.this;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
if(position < getCount()-1)
imageView.setImageResource(mImages[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
and then:
public void onCreate(Bundle savedInstanceState){
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
ViewPager viewPager = (ViewPager) findViewById(R.id.view_pager);
ImagePagerAdapter adapter = new ImagePagerAdapter();
viewPager.setAdapter(adapter);
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position)
{
if(position==viewPager.getAdapter().getCount()-1){
//start next Activity
}
}
});
}
I got it clear as #Chol said I just made the count to -1 as below.
viewPager.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
if(position==viewPager.getAdapter().getCount()-1){
Intent reg = new
Intent(Illustrations.this,Register_Page.class);
startActivity(reg);
}
}
#Override
public void onPageScrollStateChanged(int arg0) {
// TODO Auto-generated method stub
}
#Override
public void onPageScrolled(int arg0, float arg1, int arg2) {
// TODO Auto-generated method stub
}
});
}
Thank you all very much ... :)
The position is image's position that comes array like slide_image[position]. So, with using position, the Intent can be create at the SliderAdapter page just writing several code.
#Override
public Object instantiateItem(final ViewGroup container, final int position) {
layoutInflater =(LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View view = layoutInflater.inflate(R.layout.layout, container, false);
LinearLayout layoutslide = view.findViewById(R.id.slider);
ImageView slideImageView =(ImageView)view.findViewById(R.id.slide_image);
TextView slideHeading=(TextView)view.findViewById(R.id.slide_heading);
TextView slideDescription=(TextView)view.findViewById(R.id.slide_desc);
slideImageView.setImageResource(slide_image[position]);
slideHeading.setText(slide_headings[position]);
slideDescription.setText(slide_description[position]);
slideImageView.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (position == 0) {
Intent myIntent = new Intent(context,EarthQuakeActivity.class);
context.startActivity(myIntent);
}
if (position == 1) {
Intent myIntent = new Intent(context,EarthQuakeActivity.class);
context.startActivity(myIntent);
}
if (position == 2) {
Intent myIntent = new Intent(context,EarthQuakeActivity.class);
context.startActivity(myIntent);
}
}
});
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.
I am currently using TouchImageView to allow zooming in and out but now, I need also a View Pager using image view. How do I merge those two together? must I inflate the layout?
this is my viewpager
public class Main extends FragmentActivity implements AdapterView.OnItemSelectedListener, ViewPager.OnPageChangeListener{
private ViewPager viewPager;
String[] mImageIds;
private Handler handler;
/**
* Called when the activity is first created.
*/
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
displayImage();
viewPager = (ViewPager) findViewById(R.id.view_pager);
viewPager.setAdapter(new MyAdapter(getSupportFragmentManager()));
viewPager.setOnPageChangeListener(this);
//gallery = (Gallery) findViewById(R.id.gallery);
//gallery.setAdapter(new ImageAdapter());
//gallery.setOnItemSelectedListener(this);
//textView = (TextView) findViewById(R.id.title);
handler = new Handler();
}
public void displayImage()
{
ArrayList<String> mStringList= new ArrayList<String>();
File strPath = new File(Environment.getExternalStorageDirectory() + "/Covers");
int lists = strPath.listFiles().length;
Log.d("number of items in array ",String.valueOf(lists));
File yourDir = new File(strPath, "");
for (File f : yourDir.listFiles()) {
if (f.isFile())
{
String name = f.getName();
String v = strPath + "/" + name;
mStringList.add(v);
}
}
mImageIds = new String[mStringList.size()];
mImageIds = mStringList.toArray(mImageIds);
for(int i = 0; i < mImageIds.length ; i++){
//Log.d("string is",(mImageIds[i]));
}
}
// gallery item selected
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
updateUI(i);
}
// view pager item selected
public void onPageSelected(int i) {
updateUI(i);
}
private void updateUI(final int i) {
handler.post(new Runnable() {
public void run() {
//gallery.setSelection(i);
viewPager.setCurrentItem(i);
///textView.setText("Photo #" + i);
}
});
}
public void onNothingSelected(AdapterView<?> adapterView) { }
public void onPageScrolled(int i, float v, int i1) { }
public void onPageScrollStateChanged(int i) { }
public class ImageAdapter extends BaseAdapter implements OnTouchListener {
public int getCount() {
return mImageIds.length;
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ImageView imageView = new ImageView(Main.this);
imageView.setOnTouchListener(this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
imageView.setLayoutParams(new Gallery.LayoutParams(150, 100));
imageView.setScaleType(ImageView.ScaleType.FIT_XY);
return imageView;
}
#Override
public boolean onTouch(View v, MotionEvent event) {
// TODO Auto-generated method stub
return false;
}
}
public class EnableDisableViewPager extends ViewPager {
private boolean enabled = true;
public EnableDisableViewPager(Context context, AttributeSet attrs) {
super(context, attrs);
}
#Override
public boolean onInterceptTouchEvent(MotionEvent arg0) {
if(enabled)
return super.onInterceptTouchEvent(arg0);
return false;
}
public boolean isEnabled() {
return enabled;
}
public void setEnabled(boolean enabled) {
this.enabled = enabled;
}
}
public class MyAdapter extends FragmentPagerAdapter {
public MyAdapter(FragmentManager fm) {
super(fm);
}
#Override
public int getCount() {
return mImageIds.length;
}
#Override
public Fragment getItem(final int position) {
return new Fragment() {
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
ImageView imageView = new ImageView(Main.this);
imageView.setImageDrawable(Drawable.createFromPath(mImageIds[position]));
return imageView;
}
};
}
}
}
and its xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
>
<FrameLayout android:layout_height="0px"
android:layout_width="fill_parent"
android:layout_weight="1"
>
<android.support.v4.view.ViewPager
android:id="#+id/view_pager"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dip" />
</FrameLayout>
</LinearLayout>
Create an FragmentActivity whose layout consists of View Pager.
Add a Fragment foreach image whose layout consists of
TouchImageView.
Add these list of fragments to the View pager. Thats it. Pinch Zoom and pager both works.
Like this:
#Override
protected void onStart() {
super.onStart();
List<Fragment> fragments = new Vector<Fragment>();
String url1 = "someurl1.jpg";
Bundle Image1 = new Bundle();
Image1.putString("image_url", url1);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image1));
String url2 = "someurl2.jpg";
Bundle Image2 = new Bundle();
Image2.putString("image_url", url2);
fragments.add(Fragment.instantiate(this, ZoomImageFragment.class.getName(),Image2));
//and so on.
this.mPagerAdapter = new PagerAdapter(super.getSupportFragmentManager(), fragments);
mPager = (ViewPager) findViewById(R.id.pager);
mPager.animate();
mPager.setAdapter(this.mPagerAdapter);
}