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

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.

Related

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 convert ViewPager implementation using Data binding?

MainActvity:
public class MainActivity extends AppCompatActivity {
private static int currentPage = 0;
private static int NUM_PAGES = 0;
CirclePageIndicator indicator;
int Imageitems[] = {R.drawable.hike, R.drawable.hike, R.drawable.hike};
final ArrayList<Integer> imageItems = new ArrayList<>();
ViewPager mPager;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mPager = (ViewPager) findViewById(R.id.pager);
indicator = (CirclePageIndicator)
findViewById(R.id.indicator);
for (int i = 0; i < Imageitems.length; i++) {
imageItems.add(Imageitems[i]);
}
ImageSlider(imageItems);
}
private void ImageSlider(ArrayList<Integer> ImagesArray) {
mPager.setAdapter(new Item_SlidingImage_Adapter(this, ImagesArray));
indicator.setViewPager(mPager);
final float density = getResources().getDisplayMetrics().density;
indicator.setRadius(5 * density);
NUM_PAGES = ImagesArray.size();
// Auto start of viewpager
final Handler handler = new Handler();
final Runnable Update = new Runnable() {
public void run() {
if (currentPage == NUM_PAGES) {
currentPage = 0;
}
mPager.setCurrentItem(currentPage++, true);
}
};
Timer swipeTimer = new Timer();
swipeTimer.schedule(new TimerTask() {
#Override
public void run() {
handler.post(Update);
}
}, 3000, 3000);
// Pager listener over indicator
indicator.setOnPageChangeListener(new ViewPager.OnPageChangeListener() {
#Override
public void onPageSelected(int position) {
currentPage = position;
}
#Override
public void onPageScrolled(int pos, float arg1, int arg2) {
}
#Override
public void onPageScrollStateChanged(int pos) {
}
});
}
}
layout:
<?xml version="1.0" encoding="utf-8"?>
<layout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
xmlns:app="http://schemas.android.com/apk/res-auto"
tools:context=".MainActivity">
<data>
</data>
<LinearLayout
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">
<RelativeLayout
android:id="#+id/relativelayout1"
android:layout_width="match_parent"
android:layout_height="150dp"
>
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentTop="true"
android:addOnPageChangeListener="#{data.pageChangeListener}"
app:currentItem="#{data.currentPage}"
app:adapter="#{image_adapter}"
/>
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_centerHorizontal="true"
android:padding="5dp"
app:centered="true"
app:fillColor="#ff0099"
app:pageColor="#FF0000"
app:radius="#{data.density}"
app:snap="false" />
</RelativeLayout>
</LinearLayout>
</layout>
adapter:
public class Item_SlidingImage_Adapter extends PagerAdapter {
private ArrayList<Integer> IMAGES;
private LayoutInflater inflater;
private Context context;
public Item_SlidingImage_Adapter(Context context, ArrayList<Integer> IMAGES) {
this.context = context;
this.IMAGES = IMAGES;
inflater = LayoutInflater.from(context);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((View) object);
}
#Override
public int getCount() {
return IMAGES.size();
}
#Override
public Object instantiateItem(ViewGroup view, final int position) {
View imageLayout = inflater.inflate(R.layout.slidingimages_layout, view, false);
assert imageLayout != null;
final ImageView imageView = (ImageView) imageLayout
.findViewById(R.id.image);
imageView.setImageResource(IMAGES.get(position));
view.addView(imageLayout, 0);
return imageLayout;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view.equals(object);
}
#Override
public void restoreState(Parcelable state, ClassLoader loader) {
}
#Override
public Parcelable saveState() {
return null;
}
}
item.xml
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:padding="1dip" >
<ImageView
android:id="#+id/image"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:adjustViewBounds="true"
android:layout_gravity="center"
android:scaleType="fitXY" />
</FrameLayout>
Using given code I am able to auto flip in ViewPager and also using manually with some delay. I have to convert same code using Databinding; I tried but I am not able to understand how to set adapter,currentitem, and on page change listener how I will set value in xml?
How can I convert existing code for databinding in Android?

Android Shared Element Transitions between two ViewPagers

I'm trying to achieve the following:
I have an item view that displays a ViewPager with images of that item and some other information. When the user taps one of the ViewPager's images, I'd like there to be a transition between the image on the first screen and the same image on another ViewPager in a new Activity.
So far, I've managed to get the basic functionality working but there are a couple of key things that do not work as expected:
The transition from ViewPager A to the second Activity with ViewPager B only works when tapping the image at index 0 or 1 in ViewPager A.
There is a return animation when pressing back from ViewPager B in the new Activity - as long as I do not swipe to another image so the transition is from the full screen mode I'd be displaying in ViewPager B to the same image in ViewPager A. When swiping to another image and pressing back - there's no animation.
Number 1 is happening because the first couple of pages of the ViewPager are instantiated when it's created so the instantiateItem method of the Adapter gets called for each of these and this is where I'm setting the transitionName.
This is proven by the fact that calling this on the ViewPager makes that issue go away and the entry animation works on all screens:
detailPager.setOffscreenPageLimit(largeNumber);
Obviously this is unsustainable, I'd much rather not have such a high off screen limit.
My question is twofold:
How do I achieve the animation for each ViewPager item without keeping all the pages in memory via the above hack?
How can I ensure that a return transition takes place when swiping to another page in ViewPager B?
I've included my code below:
ItemActivity
public class ItemActivity extends AppCompatActivity {
private static final String ITEM_TAG = "item_tag";
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_with_fragment_container);
ButterKnife.bind(this);
if (savedInstanceState == null) {
attachFragment();
}
}
private void attachFragment() {
getSupportFragmentManager().beginTransaction()
.replace(R.id.fragment_container, ItemFragment.newInstance(), ITEM_TAG)
.commit();
}
#Override
public void onActivityReenter(int resultCode, Intent data) {
super.onActivityReenter(resultCode, data);
ItemFragment fragment = (ItemFragment) getSupportFragmentManager().findFragmentByTag(ITEM_TAG);
if (fragment != null) {
fragment.onReenter(data);
}
}}
ItemFragment - This is where the first ViewPager is
public class ItemFragment extends Fragment implements MyAdapter.MyListener {
public static final String EXTRA_STARTING_ALBUM_POSITION = "extra_starting_item_position";
public static final String EXTRA_CURRENT_ALBUM_POSITION = "extra_current_item_position";
public static final String[] IMAGE_NAMES = {"One", "two", "three", "four", "five", "six", "seven", "eight", "nine", "ten"};
private static final int FULL_SCREEN_CODE = 1234;
private Unbinder unbinder;
private Bundle tempReenterState;
private final SharedElementCallback callback = new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (tempReenterState != null) {
int startingPosition = tempReenterState.getInt(EXTRA_STARTING_ALBUM_POSITION);
int currentPosition = tempReenterState.getInt(EXTRA_CURRENT_ALBUM_POSITION);
if (startingPosition != currentPosition) {
String newTransitionName = IMAGE_NAMES[currentPosition];
View newSharedElement = detailPager.findViewWithTag(newTransitionName);
if (newSharedElement != null) {
names.clear();
names.add(newTransitionName);
sharedElements.clear();
sharedElements.put(newTransitionName, newSharedElement);
}
}
tempReenterState = null;
} else {
View navigationBar = getActivity().findViewById(android.R.id.navigationBarBackground);
View statusBar = getActivity().findViewById(android.R.id.statusBarBackground);
if (navigationBar != null) {
names.add(navigationBar.getTransitionName());
sharedElements.put(navigationBar.getTransitionName(), navigationBar);
}
if (statusBar != null) {
names.add(statusBar.getTransitionName());
sharedElements.put(statusBar.getTransitionName(), statusBar);
}
}
}
};
private List<String> images = Arrays.asList("http://wowslider.com/sliders/demo-9/data/images/1293441583_nature_forest_morning_in_the_forest_015232_.jpg",
"http://wowslider.com/sliders/demo-18/data1/images/hongkong1081704.jpg",
"http://www.irishtimes.com/polopoly_fs/1.2614603.1461003507!/image/image.jpg_gen/derivatives/box_620_330/image.jpg",
"http://weknowyourdreams.com/images/sky/sky-05.jpg");
#BindView(R.id.detail_pager)
ViewPager detailPager;
public static ItemFragment newInstance() {
return new ItemFragment();
}
#Nullable
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_image_detail, container, false);
unbinder = ButterKnife.bind(this, view);
return view;
}
#Override
public void onViewCreated(View view, #Nullable Bundle savedInstanceState) {
super.onViewCreated(view, savedInstanceState);
ActivityCompat.setExitSharedElementCallback(getActivity(), callback);
detailPager.setAdapter(new MyAdapter(getActivity(), images, this));
}
#Override
public void goFullScreen(final int position, View view) {
Intent intent = FullScreenActivity.newIntent(getActivity(), position, images);
startActivityForResult(intent, FULL_SCREEN_CODE, ActivityOptions.makeSceneTransitionAnimation(getActivity(), view, view.getTransitionName()).toBundle());
}
public void onReenter(Intent data) {
tempReenterState = new Bundle(data.getExtras());
int startingPosition = tempReenterState.getInt(EXTRA_STARTING_ALBUM_POSITION);
int currentPosition = tempReenterState.getInt(EXTRA_CURRENT_ALBUM_POSITION);
if (startingPosition != currentPosition) {
detailPager.setCurrentItem(currentPosition, false);
}
ActivityCompat.postponeEnterTransition(getActivity());
detailPager.post(new Runnable() {
#Override
public void run() {
ActivityCompat.startPostponedEnterTransition(getActivity());
}
});
}
#Override
public void onDestroyView() {
super.onDestroyView();
if (unbinder != null) {
unbinder.unbind();
}
}
}
FullScreenActivity - This is where the second ViewPager is housed
public class FullScreenActivity extends AppCompatActivity {
private final SharedElementCallback callback = new SharedElementCallback() {
#Override
public void onMapSharedElements(List<String> names, Map<String, View> sharedElements) {
if (mIsReturning) {
if (currentImage == null) {
// If shared element is null, then it has been scrolled off screen and
// no longer visible. In this case we cancel the shared element transition by
// removing the shared element from the shared elements map.
names.clear();
sharedElements.clear();
} else if (selectedIndex != mCurrentPosition) {
// If the user has swiped to a different ViewPager page, then we need to
// remove the old shared element and replace it with the new shared element
// that should be transitioned instead.
names.clear();
names.add(currentImage.getTransitionName());
sharedElements.clear();
sharedElements.put(currentImage.getTransitionName(), currentImage);
}
}
}
};
private boolean mIsReturning;
private int mCurrentPosition;
private int selectedIndex;
private static final String ARG_PRESELECTED_INDEX = "arg_preselected_index";
private static final String ARG_GALLERY_IMAGES = "arg_gallery_images";
public static final String KEY_SELECTED_IMAGE_INDEX = "key_selected_image_index";
public static final String KEY_RETAINED_IMAGES = "key_retained_images";
private static final int DEFAULT_SELECTED_INDEX = 0;
private List<String> images;
private ImageAdapter adapter;
private ImageView currentImage;
#BindView(R.id.full_screen_pager)
ViewPager viewPager;
public static Intent newIntent(#NonNull final Context context, final int selectedIndex, #NonNull final List<String> images) {
Intent intent = new Intent(context, FullScreenActivity.class);
intent.putExtra(ARG_PRESELECTED_INDEX, selectedIndex);
intent.putStringArrayListExtra(ARG_GALLERY_IMAGES, new ArrayList<>(images));
return intent;
}
#CallSuper
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout_full_screen);
ButterKnife.bind(this);
ActivityCompat.postponeEnterTransition(this);
ActivityCompat.setExitSharedElementCallback(this, callback);
if (savedInstanceState == null) {
selectedIndex = getIntent().getIntExtra(ARG_PRESELECTED_INDEX, 0);
mCurrentPosition = selectedIndex;
images = getIntent().getStringArrayListExtra(ARG_GALLERY_IMAGES);
} else {
selectedIndex = savedInstanceState.getInt(KEY_SELECTED_IMAGE_INDEX);
images = savedInstanceState.getStringArrayList(KEY_RETAINED_IMAGES);
}
setupViewPager(selectedIndex, images);
}
private void setupViewPager(final int selectedIndex, List<String> images) {
adapter = new ImageAdapter(this, images);
viewPager.post(new Runnable() {
#Override
public void run() {
viewPager.setAdapter(adapter);
viewPager.setCurrentItem(selectedIndex);
viewPager.addOnPageChangeListener(new ViewPager.SimpleOnPageChangeListener() {
#Override
public void onPageSelected(int position) {
mCurrentPosition = position;
}
});
ActivityCompat.startPostponedEnterTransition(FullScreenActivity.this);
}
});
}
#Override
public void finishAfterTransition() {
mIsReturning = true;
Intent data = new Intent();
data.putExtra(EXTRA_STARTING_ALBUM_POSITION, selectedIndex);
data.putExtra(EXTRA_CURRENT_ALBUM_POSITION, viewPager.getCurrentItem());
setResult(RESULT_OK, data);
super.finishAfterTransition();
}
private class ImageAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final List<String> images;
private ImageLoader<ImageView> imageLoader;
public ImageAdapter(Context context, List<String> images) {
this.imageLoader = new PicassoImageLoader(context);
this.images = images;
this.layoutInflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
final ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.full_image, container, false);
imageView.setTransitionName(IMAGE_NAMES[position]);
imageView.setTag(IMAGE_NAMES[position]);
imageLoader.loadImage(images.get(position), imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public void setPrimaryItem(ViewGroup container, int position, Object object) {
super.setPrimaryItem(container, position, object);
currentImage = (ImageView) object;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
}
MyAdapter
public class MyAdapter extends PagerAdapter {
private final LayoutInflater layoutInflater;
private final List<String> images;
private final MyListener listener;
private ImageLoader<ImageView> imageLoader;
public interface MyListener {
void goFullScreen(final int position, View selected);
}
public MyAdapter(Context context, List<String> images, MyListener listener) {
this.imageLoader = new PicassoImageLoader(context);
this.layoutInflater = LayoutInflater.from(context);
this.images = images;
this.listener = listener;
}
#Override
public int getCount() {
return images.size();
}
#Override
public Object instantiateItem(ViewGroup container, final int position) {
final ImageView imageView = (ImageView) layoutInflater.inflate(R.layout.pager_item_image_thing, container, false);
imageView.setTransitionName(IMAGE_NAMES[position]);
imageView.setTag(IMAGE_NAMES[position]);
if (listener != null) {
imageView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
listener.goFullScreen(position, imageView);
}
});
}
imageLoader.loadImage(images.get(position), imageView);
container.addView(imageView);
return imageView;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((ImageView) object);
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == object;
}
}
ImageLoader
public interface ImageLoader<T extends ImageView> {
void loadImage(#NonNull final Uri imageSource, #NonNull final T imageView);
void loadImage(#NonNull final String imageSource, #NonNull final T imageView);
}
PicassoImageLoader
public class PicassoImageLoader implements ImageLoader {
private final Context context;
public PicassoImageLoader(#NonNull final Context context) {
this.context = context;
}
#Override
public void loadImage(#NonNull Uri imageSource, #NonNull ImageView imageView) {
Picasso.with(context).load(imageSource).into(imageView);
}
#Override
public void loadImage(#NonNull String imageSource, #NonNull ImageView imageView) {
Picasso.with(context).load(imageSource).into(imageView);
}
}
XML Layouts
fragment_image_detail.xml
<?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">
<android.support.v4.view.ViewPager
android:id="#+id/detail_pager"
android:layout_width="match_parent"
android:layout_height="390dp" />
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="This is the title"/>
<TextView
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Some other descriptive text about things"/>
</LinearLayout>
layout_full_screen.xml
<?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">
<android.support.v4.view.ViewPager
android:id="#+id/full_screen_pager"
android:layout_width="match_parent"
android:layout_height="match_parent" />
</LinearLayout>
pager_item_thing.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/pager_item_image"
android:layout_width="match_parent"
android:layout_height="200dp"
android:foreground="?android:attr/selectableItemBackgroundBorderless"
android:layout_marginBottom="16dp" />
full_image.xml
<?xml version="1.0" encoding="utf-8"?>
<ImageView xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/full_image_view"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical" />

image swiping not working in android view pager

I want to create an app which swipe images left/right so i use viewPager for this i run this code it gets run successfully but blank screen comes nothing happens.
This is my homeSwipe Class
public class homeSwipe extends Activity {
ViewPager viewPager;
customPagerAdapter customPagerAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_home_swipe);
viewPager = (ViewPager) findViewById(R.id.pager);
customPagerAdapter = new customPagerAdapter(homeSwipe.this);
viewPager.setAdapter(customPagerAdapter);
}
}
that is my layout.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"
android:orientation="vertical">
<android.support.v4.view.ViewPager 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"
android:id="#+id/pager">
</android.support.v4.view.ViewPager>
</RelativeLayout>
This is my customPagerAdapter class
public class customPagerAdapter extends PagerAdapter {
private int imgres[] ={R.drawable.graypatternbackground,R.drawable.home,R.drawable.homescreen,R.drawable.redwall};
private Context context;
private LayoutInflater layoutInflater;
public customPagerAdapter(Context context){
this.context =context;
}
#Override
public int getCount() {
return imgres.length;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return (view == (LinearLayout)object);
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
layoutInflater = (LayoutInflater)context.getSystemService(context.LAYOUT_INFLATER_SERVICE);
View item_view =(View)layoutInflater.inflate(R.layout.swipelayout,container,false);
ImageView imgView = (ImageView)item_view.findViewById(R.id.imageView);
imgView.setImageResource(imgres[position]);
return item_view;
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
container.removeView((LinearLayout)object);
}
}
This is my swipelayout.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="match_parent"
android:layout_height="match_parent">
<ImageView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/imageView"/>
</LinearLayout>
This is custompagerAdapter.
import android.support.v4.app.Fragment;import android.support.v4.app.FragmentManager;import android.support.v4.app.FragmentStatePagerAdapter;public class PropTypePagerAdapter extends FragmentStatePagerAdapter { int noOfTab; public PropTypePagerAdapter(FragmentManager fm ,int noOfTab) { super(fm); this.noOfTab=noOfTab; } #Override public Fragment getItem(int position) { switch (position) { case 0: return new PropTabType(0); case 1: return new PropTabType(1); case 2: return new PropTabType(2); case 3: PropTabType service = new PropTabType(3); return service; } } #Override public int getCount() {
return noOfTab;
}
}
And this is logic for swapping image
public View onCreateView(LayoutInflater inflater, ViewGroup container,Bundle savedInstanceState) {view = inflater.inflate(R.layout.fragment_prop_type_tab,container, false);fragImg = (ImageView) view.findViewById(R.id.fragImg); if (position == 0) { fragImg.setImageResource(R.drawable.buy); } else if (position == 1) { fragImg.setImageResource(R.drawable.rent1); } else { fragImg.setImageResource(R.drawable.hostel); } return view; }

padding_medium cannot be resolved or is not a field error

I have a view pager to view images in Swipe horizontal fashion. I am populating view pager with my ImageFragmentAdapter class which extends FragmentPagerAdapter. In my ImageFragmentAdapter .java, i am gettin an error in this line
int padding = context.getResources().getDimensionPixelSize(R.dimen.padding_medium);
Error is : padding_medium cannot be resolved or is not a field
I just googled about the issue, I came to know that i should add this line to imports.
import your.application.packagename.R;
But still i get error on this line. can anyone tell what is the problem.?
ImageFragmentAdapter .java
public class ImageFragmentAdapter extends FragmentPagerAdapter implements
IconPagerAdapter
{
private int[] CONTENT = new int[] {
R.drawable.gallery_photo_1,
R.drawable.gallery_photo_2,
R.drawable.gallery_photo_3,
R.drawable.gallery_photo_4
};
protected static final int[] ICONS = new int[] { R.drawable.marker,
R.drawable.marker, R.drawable.marker, R.drawable.marker };
private int mCount = CONTENT.length;
public ImageFragmentAdapter(FragmentManager fm) {
super(fm);
}
#Override
public Fragment getItem(int position) {
return ImageFragment.newInstance(CONTENT[position % CONTENT.length]);
}
#Override
public int getCount() {
return mCount;
}
#Override
public Object instantiateItem(ViewGroup container, int position) {
Context context = MainActivity.appContext;
ImageView imageView = new ImageView(context);
int padding = context.getResources().getDimensionPixelSize(
R.dimen.padding_medium);//error//
imageView.setPadding(padding, padding, padding, padding);
imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
imageView.setImageResource(CONTENT[position]);
((ViewPager) container).addView(imageView, 0);
return imageView;
}
#Override
public boolean isViewFromObject(View view, Object object) {
return view == ((ImageView) object);
}
#Override
public void destroyItem(ViewGroup container, int position, Object object) {
((ViewPager) container).removeView((ImageView) object);
}
/*
#Override
public CharSequence getPageTitle(int position) {
return ImageFragmentAdapter.CONTENT[position % CONTENT.length];
}
*/
#Override
public int getIconResId(int index) {
return ICONS[index % ICONS.length];
}
public void setCount(int count) {
if (count > 0 && count <= 10) {
mCount = count;
notifyDataSetChanged();
}
}
}
I use DetailsFragment.java to populate the View pager onto fragment_details.xml
public class DetailsFragment extends SherlockFragment
{
public static final String TAG = "detailsFragment";
ImageFragmentAdapter mAdapter;
ViewPager mPager;
PageIndicator mIndicator;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState)
{
//container.removeAllViews();
// TODO Auto-generated method stub
View view = inflater.inflate(R.layout.fragment_details, container,
false);
mAdapter = new ImageFragmentAdapter(getActivity().getSupportFragmentManager());
mPager = (ViewPager) view.findViewById(R.id.pager);
mPager.setAdapter(mAdapter);
mIndicator = (CirclePageIndicator) view.findViewById(R.id.indicator);
mIndicator.setViewPager(mPager);
return view;
}
}
fragment_details.xml
<?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" >
<android.support.v4.view.ViewPager
android:id="#+id/pager"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_weight="1" />
<com.viewpagerindicator.CirclePageIndicator
android:id="#+id/indicator"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:padding="10dip" />
</LinearLayout>

Categories

Resources