请选择 进入手机版 | 继续访问电脑版

网络科技

    今日:39| 主题:272259
收藏本版
互联网、科技极客的综合动态。

[其他] How to build an image gallery app – full tutorial with code

[复制链接]
不忘初心 发表于 2016-10-4 01:55:21
419 12

立即注册CoLaBug.com会员,免费获得投稿人的专业资料,享用更多功能,玩转个人品牌!

您需要 登录 才可以下载或查看,没有帐号?立即注册

x

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-1-网络科技-Android,different,something,learning,exercise

  There are many reasons you might find yourself needing to create an image gallery – whether it’s to show off album covers for a music app, to present feature images for articles in a feed, or to showcase your work in a portfolio. To make the right impression though, these apps should allow users to effortlessly swipe through multiple images without slowdown and that’s where things get a little tricky.
   This tutorial will show you how to create a seamless gallery filled with nice big images and then adapt that for a number of different applications. Along the way, we’ll see how to use RecyclerViews , adapters and Picasso – so hopefully it will make for a great learning exercise, whatever you end up doing with it! Full code and project included below…
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-2-网络科技-Android,different,something,learning,exercise
   See also: Using RecyclerView to build lists in Android     Introducing RecyclerView

   To create our Android gallery, we’re going to use something called a RecyclerView . This is a handy view that acts very much like a ListView but with the advantage of allowing us to scroll quickly through large data sets. It does this by only loading the images that are currently in view at any given time. This means we can load more images without the app becoming very slow. There’s a lot more that you can do with this view and it’s used all over Google’s own apps, so check out the full explanation tousing RecyclerView to find out more.
   The good news is that this is all we really need to create our gallery – a RecyclerView filled with images. The bad news is that the RecyclerView is a little more complicated than most other views. Because of course it is.
   RecyclerView is not, for starters, available to drag and drop using the design view. So we’ll just have to add it to the activity_main.xml , like so:
  1. <android.support.v7.widget.RecyclerView
  2.             android:id="@+id/imagegallery"
  3.             android:layout_width="match_parent"
  4.             android:layout_height="match_parent"
  5.             />
复制代码
  Notice that we’re referencing the Android Support Library. This means we also need to modify our build.gradle in order to include the dependency. Just add this line to the app level file:
  1. compile 'com.android.support:recyclerview-v7:24.2.1'
复制代码
And if that’s not installed, then you’re going to have to open the SDK manager and install it. Fortunately, Android Studio is pretty smart about prompting you to do all this. I just got a new computer, so I can play along with you!
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-3-网络科技-Android,different,something,learning,exercise

  Head back to the XML and it should now be working just fine. Except the list is not populated except with ‘item 1, item 2, item 3’. What we need to do, is load our images into here.
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-4-网络科技-Android,different,something,learning,exercise

  Creating your list of images

  As mentioned, populating our recycler view is a little more complicated than using a regular list. By which, I mean it’s way more complicated… but it’s a great chance for us to learn some handy new skills. So there’s that.
   For a RecyclerView , we’re also going to need a layout manager and an adapter. This is what’s going to allow us to organize the information in our view and add the images. We’ll start by initializing our views and attaching an adapter in the onCreate of MainActivity.java . This looks like so:
  1. setContentView(R.layout.activity_main);
  2. RecyclerView recyclerView = (RecyclerView)findViewById(R.id.imagegallery);
  3. recyclerView.setHasFixedSize(true);
  4. RecyclerView.LayoutManager layoutManager = new GridLayoutManager(getApplicationContext(),2);
  5. recyclerView.setLayoutManager(layoutManager);
  6. ArrayList<CreateList> createLists = prepareData();
  7. MyAdapter adapter = new MyAdapter(getApplicationContext(), createLists);
  8. recyclerView.setAdapter(adapter);
复制代码
  We’re setting the layout as activity_main , then we’re finding the RecyclerView and initializing it. Notice that we use HasFixedSize to make sure that it won’t stretch to accommodate the content. We’re also creating the layout manager and the adapter here. There are multiple types of layout manager but true to gallery-form, we’re going to pick a grid rather than a long list. Remember to import the GridLayoutManager and the RecyclerView as Android Studio prompts you to do so. Meanwhile, when you highlight MyAdapter , you’ll be given the option to ‘Create Class MyAdapter’. Go for it – make your own MyAdapter.Java and then switch back. We’ll come back to this later.
   Before we can use the new adapter class, we first need to create our data set. This is going to take the form of an array list. So in other words, we’re going to place a list of all our images in here, which the adapter will then read and use to fill out the RecyclerView .
   Just to make life a little more complicated, creating the Array List is also going to require a new class. First though, create a string array and an integer array in the same MainActivity.Java :
  1. private final String image_titles[] = {
  2.         "Img1",
  3.         "Img2",
  4.         "Img3",
  5.         "Img4",
  6.         "Img5",
  7.         "Img6",
  8.         "Img7",
  9.         "Img8",
  10.         "Img9",
  11.         "Img10",
  12.         "Img11",
  13.         "Img12",
  14.         "Img13",
  15. };
  16. private final Integer image_ids[] = {
  17.         R.drawable.img1,
  18.         R.drawable.img2,
  19.         R.drawable.img3,
  20.         R.drawable.img4,
  21.         R.drawable.img5,
  22.         R.drawable.img6,
  23.         R.drawable.img7,
  24.         R.drawable.img8,
  25.         R.drawable.img9,
  26.         R.drawable.img10,
  27.         R.drawable.img11,
  28.         R.drawable.img12,
  29.         R.drawable.img13,
  30. };
复制代码
  The strings can be anything you want – these will be the titles of your images. As for the integers, these are image IDs. This means they need to point to images in your Drawables folder. Drop some images into there that aren’t too massive and make sure the names are all correct.
   Remember: a list is a collection of variables (like strings or integers), whereas an array is more like a filing cabinet of variables. By creating an ArrayList then, we’re basically creating a list of filing cabinets, allowing us to store two collections of data in one place. In this case, the data is a selection of image titles and image IDs.
   Now create a new Java Class called CreateList and add this code:
  1. public class CreateList {
  2.     private String image_title;
  3.     private Integer image_id;
  4.     public String getImage_title() {
  5.         return image_title;
  6.     }
  7.     public void setImage_title(String android_version_name) {
  8.         this.image_title = android_version_name;
  9.     }
  10.     public Integer getImage_ID() {
  11.         return image_id;
  12.     }
  13.     public void setImage_ID(Integer android_image_url) {
  14.         this.image_id = android_image_url;
  15.     }
  16. }
复制代码
  What we have here is a method we can use to add new elements ( setImage_title, setImage_ID ) and retrieve them ( getImage_title, getImage_ID ). This will let us run through the two arrays we made and stick them into the ArrayList. You’ll need to import array lists.
  We do this, like so:
  1. private ArrayList<CreateList> prepareData(){
  2.         ArrayList<CreateList> theimage = new ArrayList<>();
  3.         for(int i = 0; i< image_titles.length; i++){
  4.             CreateList createList = new CreateList();
  5.             createList.setImage_title(image_titles[i]);
  6.             createList.setImage_ID(image_ids[i]);
  7.             theimage.add(createList);
  8.         }
  9.         return theimage;
  10.     }
  11. }
复制代码
  So we’re performing a loop while we go through all the image titles and adding them to the correct array in the ArrayList one at a time. Each time, we’re using the same index ( i ), in order to add the image ID to its respective location.
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-5-网络科技-Android,different,something,learning,exercise

  Confused yet?
  Using the adapter

   Before you head over to MyAdapter.java , you first need to create a new XML layout in the layout directory. I’ve called mine cell_layout.xml and it looks like so:
  1. <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
  2.     android:orientation="vertical"
  3.     android:background="#FFFFFF"
  4.     android:layout_width="match_parent"
  5.     android:layout_height="wrap_content">
  6.     <ImageView
  7.         android:id="@+id/img"
  8.         android:adjustViewBounds="true"
  9.         android:layout_width="match_parent" />
  10.     <TextView
  11.         android:id="@+id/title"
  12.         android:layout_gravity="center"
  13.         android:textColor="#000"
  14.         android:textStyle="bold"
  15.         android:layout_width="wrap_content"
  16.         android:layout_height="wrap_content" />
  17. </LinearLayout>
复制代码
All this is, is the layout for the individual cells in our grid layout. Each one will have an image at the top, with text just underneath. Nice.
   Now you can go back to your MyAdapter.java . This is where we’re going to take the list, take the cell layout and then use both those things to fill the RecyclerView . We already attached this to the RecyclerView in MainActivity.Java , so now all that’s left is… lots and lots of complex code.
  It’s probably easiest if I just show you…
  1. public class MyAdapter extends RecyclerView.Adapter<MyAdapter.ViewHolder> {
  2.     private ArrayList<CreateList> galleryList;
  3.     private Context context;
  4.     public MyAdapter(Context context, ArrayList<CreateList> galleryList) {
  5.         this.galleryList = galleryList;
  6.         this.context = context;
  7.     }
  8.     @Override
  9.     public MyAdapter.ViewHolder onCreateViewHolder(ViewGroup viewGroup, int i) {
  10.         View view = LayoutInflater.from(viewGroup.getContext()).inflate(R.layout.cell_layout, viewGroup, false);
  11.         return new ViewHolder(view);
  12.     }
  13.     @Override
  14.     public void onBindViewHolder(MyAdapter.ViewHolder viewHolder, int i) {
  15.         viewHolder.title.setText(galleryList.get(i).getImage_title());
  16.         viewHolder.img.setScaleType(ImageView.ScaleType.CENTER_CROP);
  17.         viewHolder.img.setImageResource((galleryList.get(i).getImage_ID()));        
  18.     }
  19.     @Override
  20.     public int getItemCount() {
  21.         return galleryList.size();
  22.     }
  23.     public class ViewHolder extends RecyclerView.ViewHolder{
  24.         private TextView title;
  25.         private ImageView img;
  26.         public ViewHolder(View view) {
  27.             super(view);
  28.             title = (TextView)view.findViewById(R.id.title);
  29.             img = (ImageView) view.findViewById(R.id.img);
  30.         }
  31.     }
  32. }
复制代码
  So what we’re doing here is to get our ArrayList and then create a ViewHolder . A ViewHolder makes it easier for us to iterate lots of views without having to write findViewByID every time – which would be impractical for a very long list.
   We create the VewHolder by referencing the cell_layout file we created earlier, and then bind it with the data from our ArrayList . We find the TextView first and set that to be the relevant string, then we find the ImageView and use the image ID integer to set the image resource. Notice that I’ve also setScaleType to CENTER_CROP . This means that the image will be centered but cropped to fill the enter cell in a relatively attractive manner. There are other scale types but I believe that this is by far the most attractive for our purposes.
   Don’t forget to import the ImageView and TextView classes. And remember you need to add some images to your drawables folder. Once you’ve done that though you should be ready to go!
  Give it a try and you should end up with something that looks a little like this:
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-6-网络科技-Android,different,something,learning,exercise

  Except without all the pictures of me… This is just what I happened to have to hand, don’t judge!
   Not working as expected? Don’t worry – this is a pretty complicated app for beginners. You can find the full thing over at GitHub here and then just work through each step while referring to the code.
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-7-网络科技-Android,different,something,learning,exercise
   See also: Displaying large amounts of data with GridView and CardView     2     Making this into a useful app

  So right now we have a strange slideshow of photos of me. Not really a great app…
   So what might you use this code for? Well, there are plenty of apps that essentially boil down to galleries – this would be a great way to create a portfolio for your business for example, or perhaps a visual guide of some sort.
   In that case, we might want to add an onClick so that we can show some information, or perhaps a larger version of the image when someone taps their chosen item. To do this, we just need to import the onClickListener and then add this code to onBindViewHolder :
  1. viewHolder.img.setOnClickListener(new OnClickListener() {
  2.     @Override
  3.     public void onClick(View v) {
  4.         Toast.makeText(context,"Image",Toast.LENGTH_SHORT).show();
  5.     }
  6. });
复制代码
  If we wanted to load a selection of photos on the user’s device meanwhile, we’d simply have to list files in a particular directory. To do that, we’d just need to use listFiles to take the file names and load them into our  ListArray list, using something list this:
  1. String path = Environment.getRootDirectory().toString();
  2. File f = new File(path);
  3. File file[] = f.listFiles();
  4. for (int i=0; i < file.length; i++)
  5. {
  6.     CreateList createList = new CreateList();
  7.     createList.setImage_Location(file[i].getName());
  8. }
复制代码
Except you’ll be changing your path string to something useful, like the user’s camera roll (rather than the root directory). Then you can load the bitmaps from the images on an SD card or internal storage by using the image name and path, like so:
  1. compile 'com.android.support:recyclerview-v7:24.2.1'0
复制代码
  You’ll probably want to get thumbnails from them too. This way, the list will be populated dynamically – so that when new photos are added to that directory, you’re gallery will update to show them each time you open it. This is how you might make a gallery app for displaying the images on a user’s phone, for example.
  Or alternatively, another way we could make this app a little fancier, would be to download images from the web.
  This might sound like a whole extra chapter but it’s actually pretty simple as well. You just need to use the Picasso library, which is very easy and completely free. First, add the dependency like we did earlier:
  1. compile 'com.android.support:recyclerview-v7:24.2.1'1
复制代码
  Then, change your ArrayList to contain two string arrays instead of a string and an integer. Instead of image IDs, you’re going to fill this second string array with URLs for your images (in inverted commas). Now you just swap out the line in your onBindViewHolder to:
  1. compile 'com.android.support:recyclerview-v7:24.2.1'2
复制代码
Remember to add the relevant permission and it really is that easy – you can now download your images right from a list of URLs and that way update them on the fly without having to update the app! Picasso will also cache images to keep things nice and zippy for you.
  Note as well that if you wanted to have more than two images per row, you would simply swap:
  1. compile 'com.android.support:recyclerview-v7:24.2.1'3
复制代码
For:
  1. compile 'com.android.support:recyclerview-v7:24.2.1'4
复制代码
This will give you something like the following:
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-8-网络科技-Android,different,something,learning,exercise

   If you don’t like the text and you just want images, then you can easily remove the string array from proceedings. Or for a quick hack if you don’t want to stray too far from my code, you can just make the TextView super thin.
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-9-网络科技-Android,different,something,learning,exercise

  Closing comments

  And there you have it – your very own basic image gallery. There are plenty of uses for this and hopefully you’ve learned a few useful bits and pieces along the way. Stay tuned for more tutorials just like this one!
   And remember, the full project can be found here for your reference.
   

How to build an image gallery app – full tutorial with code

How to build an image gallery app – full tutorial with code-10-网络科技-Android,different,something,learning,exercise



上一篇:三天的时间,我用同一种元素设计了3款风格迥异的LOGO
下一篇:Apple Watch sales will be worse in 2016 than in 2015 (AAPL)
牛轧糖牛萨萨 发表于 2016-10-4 03:50:08
走过路过请支持下!
回复 支持 反对

使用道具 举报

wolagequnima 发表于 2016-10-4 03:50:08
不忘初心在马路边丢了一分钱 !  
回复 支持 反对

使用道具 举报

幼丝 发表于 2016-10-4 03:52:51
为保住菊花,这个一定得回复!
回复 支持 反对

使用道具 举报

snkteko 发表于 2016-10-4 03:54:16
小弟snkteko默默的路过贵宝地~~~
回复 支持 反对

使用道具 举报

漫无天下 发表于 2016-10-4 03:54:24
众里寻他千百度,蓦然回首在这里!
回复 支持 反对

使用道具 举报

vae蛛丝马迹 发表于 2016-10-4 04:06:33
一直在看
回复 支持 反对

使用道具 举报

jiang5495 发表于 2016-10-4 04:52:24
报告!我就是路过来看看的。。。
回复 支持 反对

使用道具 举报

●.未央灬 发表于 2016-10-4 20:59:35
前排顶,很好!
回复 支持 反对

使用道具 举报

usawoainila 发表于 2016-10-15 16:51:53
不忘初心说的我也略懂!
回复 支持 反对

使用道具 举报

*滑动验证:
您需要登录后才可以回帖 登录 | 立即注册

本版积分规则

我要投稿

推荐阅读


回页顶回复上一篇下一篇回列表
手机版/CoLaBug.com ( 粤ICP备05003221号 | 文网文[2010]257号 )

© 2001-2017 Comsenz Inc. Design: Dean. DiscuzFans.

返回顶部 返回列表