Adding multiple images to ViewPager

此生再无相见时 提交于 2020-12-08 06:10:35

问题


I'm new to Android programming. I'd like to make a very simple app where you can browse a few predefined images fullscreen. I tried the following tutorial:

https://developer.android.com/training/animation/screen-slide.html#viewpager

Android is a bit complicated to me with the .xml files for resources etc. I thought XML was just to define the individual resources, but I realized they also act similarly to HTML pages when I want to create a view. I managed to display one image by replacing the second TextView "textView" by my ImageView in activity_screen_slide.xml.

But the problem is that it now it displays the same image with each page. How can I set a different one for each page? I tried to add multiple LinearLayouts with different images, but the app crashed.

Any ideas?


回答1:


To show a different image on each slide, you'll need to add some code that defines the correct image for each page. Since you're just trying to display a few predefined images, I'm guessing that you've already loaded the images into your project's drawable directory. With that assumption in mind, I'll walk you through the missing pieces in the example you're following.

If you haven't done so already, create your ScreenSlidePageFragment class, and modify the code to look something like this:

public class ScreenSlidePageFragment extends Fragment {
private static final String ARG_RESOURCE_ID = "resource_id";
private int id; // resource id of the static image to display in this page

public ScreenSlidePageFragment() {
    // Required empty public constructor
}

// Your program should call this to create each instance of this Fragment.
public static ScreenSlidePageFragment newInstance(int id) {
    ScreenSlidePageFragment fragment = new ScreenSlidePageFragment();
    Bundle args = new Bundle();
    args.putInt(ARG_RESOURCE_ID, id);
    fragment.setArguments(args);
    return fragment;
}

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    if (getArguments() != null) {
        id = getArguments().getInt(ARG_RESOURCE_ID);
    }
}

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_screen_slide_page, container, false);
    // assign our image's resource id here
    ImageView imageView = (ImageView) view.findViewById(R.id.image);
    imageView.setImageResource(id);
    return view;
}

Because we want each fragment to display an image with a different resource id, I added a parameter (id) that you can pass to the fragment when you create it.

Now, we just need to make some minor changes to ScreenSlidePagerActivity. First, add a static array that contains the drawable image resources that you want to use. It should look something like this:

private static final int[] IMAGES = {R.drawable.image1, R.drawable.image2, R.drawable.image3, R.drawable.image4};

Finally, modify your PagerAdapter, so that getCount returns the size of your array, and getItem looks up the appropriate resource id for each page before creating each slide's fragment.

private class ScreenSlidePagerAdapter extends FragmentStatePagerAdapter {
    public ScreenSlidePagerAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public Fragment getItem(int position) {
        if (position < IMAGES.length)
            return ScreenSlidePageFragment.newInstance(IMAGES[position]);
        else
            return null;
    }

    @Override
    public int getCount() {
        return IMAGES.length;
    }
}



回答2:


This is how you go about it. Also, make sure you are using an image loading library (like Glide) to avoid OutOfMemory crashes while loading images.

    public class ImagesAdapter extends FragmentPagerAdapter {
    public ImagesAdapter(FragmentManager fm) {
        super(fm);
    }

    @Override
    public int getCount() {
        return 6; //number of images you want to display
    }

    @Override
    public Fragment getItem(int position) {
        return ImageFragment.newInstance(position);
    }
   }

    public class ImageFragment extends Fragment {

    public static ImageFragment newInstance(int position){
       Bundle bundle = new Bundle();
       bundle.putInt("IMAGE_POSITION", position);
       ImageFragment fragment = new ImageFragment();
       fragment.setArguments(bundle);
       return fragment;
    }

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        View view =  inflater.inflate(R.layout.image_fragment_layout, container, false);
int option =           getArguments().getInt("IMAGE_POSITION");
        ImageView imageView = (ImageView)view.findViewById(R.id.imageView);
        TypedArray imgs = getResources().obtainTypedArray(R.array.images);
        Glide.with(this).load(imgs.getResourceId(SAUtils.getIndex(option) - 1, -1)).into(imageView);
        imgs.recycle();
        return view;


       }
        }

//in main activity
ViewPager pager = findViewById(R.id.viewpager);
ImagesAdapter adapter = new ImagesAdapter();
pager.setAdapter(adapter);


//in resources.xml    
<integer-array name="options_icons">
        <item>@drawable/image_1</item>
        <item>@drawable/image_2</item>
        <item>@drawable/image_3</item>
        <item>@drawable/image_4</item>
        <item>@drawable/image_5</item>
        <item>@drawable/image_6</item>
    </integer-array>

//image_fragment_layout
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@android:color/transparent"
    android:orientation="vertical">

    <ImageView
        android:id="@+id/imageView"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:scaleType="fitCenter" />
        </FrameLayout>


        //main_activity_layout
               <android.support.v4.view.ViewPager
            android:id="@+id/viewpager"
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:background="@drawable/main_app_gradient"
            android:paddingBottom="56dp"
            android:visibility="visible" />



回答3:


You need to adapt this code  

@Override
        public Fragment getItem(int position) {
            return new ScreenSlidePageFragment();
        }

Then you pick one of your images according to the value of "position"

And this method needs to return your image count:  

 @Override
        public int getCount() {
            return NUM_PAGES;
        }



回答4:


If you want to add something like showcase view or a tutorial/intro view for your application with great UI and animation included, then you can use the gradle libraries for this purpose. It gives a proffessional touch to the app as well.

https://github.com/florent37/TutoShowcase
https://github.com/deano2390/MaterialShowcaseView
https://github.com/florent37/TutoShowcase



回答5:


You can also use android widget called View Flipper to Add dynamic or Static images with easy custom animations..Check this link for overview :

https://developer.android.com/reference/android/widget/ViewFlipper.html



来源:https://stackoverflow.com/questions/45786697/adding-multiple-images-to-viewpager

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!