English subtitles

← 08 Creating an Android Library

Get Embed Code
4 Languages

Showing Revision 3 created 05/25/2016 by Udacity Robot.

  1. Android libraries are essentially
    fully featured Android apps
  2. with the one restriction that they
    can't be installed by themselves.
  3. They have to be packaged into another
    app to be installed on a device.
  4. Android apps tend to consist of a whole
    lot of files, so while you can totally
  5. create an Android library by hand,
    it's a lot easier to use the wizard.
  6. Let's check out how to do that.
  7. If you right-click on
    the root of your project and
  8. select New Module > Phone and
    Tablet Applications > Android Library,
  9. you can give your library a name and
    an sdk, and then just like a normal app,
  10. you can choose what kinds of
    activities you want to add.
  11. Let's add a blank
    activity with a fragment.
  12. We'll give it a name.
  13. Now, a myLibrary folder has been
    added to the root of your project
  14. with all the familiar source and res and
  15. even a manifest that you'd associate
    with a normal Android app.
  16. Also, the wizard is nice enough to add
    your new library as a sub-project in
  17. the multi-project build.
  18. So, the last thing you need to do to be
    able to use your new activity in your
  19. base app is to head over to the
    build.gradle file in the app directory.
  20. And then we'll need to add
    a compile time dependency
  21. on the project myLibrary.
  22. That's all there is to it.
  23. Let's check out a working example.
  24. So here's the demo from the course code,
    which I strong suggest you go check out.
  25. We've added this imageactivity
    Android library to our project.
  26. This library defines an activity with
    its own layouts and with its own values,
  27. like strings.
  28. So here's the message that
    the activity's going to display.
  29. And this drawable of the Gradle logo
    is also wrapped up inside our Android
  30. library.
  31. In settings.gradle,
    imageactivity is added as a subproject,
  32. and in the build.gradle
    file of the app directory,
  33. we have a compile time dependency
    on the image activity project.
  34. So that means in the main activity
    of our main Android project,
  35. we can import image activity and
    set up an Intent to go launch it.
  36. If we go ahead and
  37. deploy that to our test device, here's
    the activity from our app module and
  38. our button which then launches
    the activity from our Android library.
  39. There we go.
  40. We've made an activity that's easy
    to reuse between applications.