【Add pictures to your Android application】

Previous: 【Create Birthday Card Application】

1. Introduction

In this article, you'll learn how to add images ImageViewto .

prerequisite

  • Learn how to create and run new apps in Android Studio.
  • Learn how to add, remove, and set properties TextViewson .

Learning Content

  • How to add a picture or photo to an Android application.
  • How to use Display pictures ImageViewin the application.
  • How to extract text into string resources for easier translation applications and reuse of strings.
  • How to make your app available to as many users as possible.

what you will build

  • Extend the Happy Birthday app to add pictures.

required conditions

  • A computer with Android Studio installed.
  • The app created in the "Create a Birthday Card app" article.

2. Set up the application

  1. Open the project you used in the previous article in Android Studio. You can use solution codes or codes that you create. After running the app, the following is displayed.

insert image description here

Add an image to an item

In this task, you will download an image from the Internet and add it to your Happy Birthday application.

  1. Click here to see an image of the birthday card on GitHub.
  2. Click the Download button on the right, and the picture will be displayed on the interface.

insert image description here

  1. Right-click the image and save the file as androidparty.png on your computer . Make a note of the save location (eg: Downloads folder).
  2. In Android Studio, click View > Tool Windows > Resource Manager in the menu , or click the Resource Manager tab on the left side of the Project window .
  3. Click the + in the upper left corner in the Resource Manager , then select Import Drawables . A file browser will open.

insert image description here

  1. In the file browser, locate the downloaded image file and click Open .
  2. Click Next . Android Studio shows you a preview of the image.
  3. Click Import .
  4. If the picture is imported successfully, Android Studio will add the picture to the Drawable list. This list contains all images and icons for the app. You can now use this image in your application.

insert image description here

  1. Click View > Tool Windows > Project in the menu or the leftmost Project tab to switch back to the project view.
  2. Expand app > res > drawable and make sure the image is in the app's drawable folder.

insert image description here

3. Add ImageView

To display an image in an app, it needs a display location. TextViewYou can use to display images just like you ImageViewdisplay text with .

In this task, you'll add to the app ImageViewand set its image as the cupcake image you downloaded. You'll then position and resize the image so it fills the entire screen.

Add ImageView and set its picture

  1. In the Project window, open activity_main.xml (click app > res > layout > activity_main.xml ).

Tip: If you don't see the layout editor, click the Design mode button in the upper right corner.
insert image description here

  1. In the layout editor , go to the Palette and ImageViewdrag onto the app, placing it near the center without overlapping any text

The Pick a Resource dialog box opens . This dialog lists all image resources available to your app. Note that birthday images are listed under the Drawable tab. Drawable resources are a general concept of graphics, referring to graphics that can be drawn on the screen, including pictures, bitmaps, icons, and many other types of drawing resources.

  1. In the Pick a Resource dialog, find the cake image from the Drawable list.
  2. Click the picture, then click OK .

insert image description here

The image will then be added to the app, but it may be placed in the wrong place without filling the screen. In this next step, you will resolve this issue.

Position the ImageView and resize it

  1. Click and drag in the layout editorImageView . As you drag, you'll see a pink rectangle border appear around the app screen in the Design view. The pink rectangle outlines the screen boundaries where the s are ImageViewplaced .
  2. Drag ImageViewto align the left and right edges with the pink rectangle. Android Studio will "snap" the image to the edge as you move closer. (You then need to snap to the top and bottom edges.)

insert image description here

ConstraintLayoutThe in Viewsneeds have horizontal and vertical constraints in order to tell ConstraintLayouthow to place those views. Next, you'll add these constraints.

Note: In the context of the layout editor , constraints represent connections or alignments between a view and other views, parent layouts, or invisible guides. For example, a view can be constrained to remain a certain distance from the edge of its container, or to always be to the right of another view, or to always be the top view inside a container.

  1. Hover the pointer over the circle on top of ImageViewthe outline and it will be highlighted along with another circle.
  2. If you drag the circle toward the top of the app screen, an arrow connects the circle to the pointer as you drag. Drag until it snaps to the top of the screen. In doing so, you ImageView've ConstraintLayoutadded a constraint between the top of the and the top of the .

insert image description here

  1. Add a constraint between the bottom of and the bottom of ImageView. ConstraintLayoutIt's possible that you won't be able to drag as you would the top because it's too close to the edge. In this case, you can add a constraint by clicking the + at the bottom of the Constraint Widget in the Attributes window. Be sure to set margins to 0.

insert image description here

Tip:Views The more you put on the screen , the harder it becomes to add constraints. If you Viewadd , you can undo it with Control+Z(on a Mac, use ). Command+ZAlternatively, right-click on the corresponding and select Clear Constraints of SelectionView from the pop-up menu to remove all constraints for that .View
insert image description here

Right now, the image is centered, but it doesn't take up the entire screen. In the next steps, you will resolve this issue.

  1. In the Constraints section under the Constraint Widget , set the layout_width to 0dp (match constraint) . 0dp is a shorthand to instruct Android Studio to use a matching constraint on the width of the . Since you just added constraints, this will make it as wide as the , with all margins subtracted.ImageViewConstraintLayout

insert image description here

  1. Set layout_height to 0dp (match constraint). Since you added constraints, which will make the ImageView as tall as the ConstraintLayout, all margins will be subtracted.
    insert image description here

  2. ImageViewAs tall and as wide as the app screen, but the image is centered ImageViewin the and has a lot of white space above and below the image. This doesn't look very nice, so ImageViewadjust the scaleType of to tell the system how to size and align the image. For more information ScaleType, see the Developer Reference Guide . The application should now look like the following.

insert image description here

Find the scaleType property. You may need to scroll down or search for the property. Try setting different values ​​for scaleType to see the effect of different values.

Tip: To find an attribute in the list of all attributes, click the magnifying glass icon to the right of "Attributes" and start typing the name of the attribute. Android Studio will only display properties that contain the entered string.
insert image description here

Once done, set scaleType to centerCrop . This way, the picture will fill the entire screen without distortion.

insert image description here

The cake image should now fill the entire screen, as shown below.

insert image description here

But now you can't see the birthday wishes and autographs. In this next step, you will resolve this issue.

Move the ImageView behind the text

ImageViewOnce the fills the entire screen, you can no longer see the text. This is because the image is now covering the text. Therefore, the order of interface elements matters. You added first TextViews, then added ImageView, which means the image view will be on top. When you add views to a layout, they are added to the end of the view list and are drawn in the order they are in the list. ImageViewis added ConstraintLayoutto Viewsthe end of the list, which means this view will be drawn last, and on top TextViewsof . To fix this, you need to change the order of the views, ImageViewmoving the beginning of the list. This way, the system draws that view first.

insert image description here

In the Component Tree , click ImageViewand drag TextViewsit above and ConstraintLayoutdirectly below the . The system displays a blue line with a triangle indicating the target location ImageViewof . Please ImageViewdrag ConstraintLayoutdirectly below .

insert image description here

The ImageView should now be at the top of the list below the ConstraintLayout, followed by the TextViews. You should be able to see the text "Happy Birthday, Sam!" and "From Emma." (Please ignore the warning about missing content descriptions for now.)

congratulations! You've added a picture to your Android app!

4. Adopt standardized coding practices

TextViewsAndroid Studio displayed a warning triangle when you added in the previous article . In this step, you will address the issues indicated by these warnings, and you will also address the issues indicated by the warnings displayed ImageViewon .

translate

When writing your app, it's important to note that your app might be translated into other languages ​​in some cases. As you learned in the previous article, a string is a sequence of characters, such as "Happy Birthday, Sam!".

Hardcoded strings are strings that are written directly in your app's code. It would make the app difficult to translate to other languages ​​and to reuse strings elsewhere in the app. You can solve this kind of problem by "extracting strings into resource files". That is, instead of hardcoding a string in your code, you put the string in a file, give the file a name, and use that name whenever you want to use the string. Even if you change the string or translate the string to another language, the name will remain the same.

insert image description here

  1. TextViewClick the orange triangle next to the first one (with "Happy Birthday, Sam!"). Android Studio will open a window with more information and suggested fixes. You may need to scroll down to see Suggested Fix ( see step 8 if there is no orange triangle ).

insert image description here

  1. Click the Fix button. Android Studio will open the Extract Resource dialog. From this dialog, you can customize the name used when calling the string resource and some details about how the resource is stored. Resource name is the name used when calling the string. Resource value is the actual content of the string itself.
  2. In the Extract Resource dialog, change the Resource name to happy_birthday_text . String resources should use lowercase names, and multiple words should be separated by underscores. Leave other settings as default.

insert image description here

  1. Click the OK button.
  2. In the Attributes pane, find the text attribute, and you'll find that Android Studio has automatically set it to @string/happy_birthday_text .

insert image description here

  1. Open strings.xml (app > res > values ​​> strings.xml ), and you will find that Android Studio has created a string resource called happy_birthday_text .
<resources>
    <string name="app_name">Happy Birthday</string>
    <string name="happy_birthday_text">Happy Birthday, Sam!</string>
</resources>

strings.xmlContains all strings that the user will see in the app. Note that the app's name is also a string resource. By having all your strings in one place, you can more easily translate all the text in your app, as well as re-use strings in different parts of your app.

  1. Follow the same steps to extract the text TextViewof , and name the string resource signature_text .

The completed file should look like this.

<resources>
    <string name="app_name">Happy Birthday</string>
    <string name="happy_birthday_text">Happy Birthday, Sam!</string>
    <string name="signature_text">From Emma.</string>
</resources>
  1. If TextViewthere is no orange triangle next to it, it may be a problem with your warning level setting, or a problem with a certain plugin. You can directly open strings.xml (app > res > values ​​> strings.xml ) and add code in it: <string name="happy_birthday_text">Happy Birthday, Sam!</string>
    the code after adding is shown in the code in step 6, and then go to the Attributes pane, find the text attribute, and set It is set to @string/happy_birthday_text. The second TextView is set in the same way

Check if an app supports accessibility features

If you follow good accessibility coding practices, it will be easier for all of your users, including those with disabilities, to navigate and interact with your app.

Note: Android provides many tools for users. For example, TalkBack is Google's screen reader that comes with Android devices. TalkBack provides spoken feedback to users so they can use their device without looking at the screen. For more information on accessibility features, see the Developer Reference Guide .

Android Studio provides hints and warnings to help you improve the accessibility of your app.

  1. In the Component Tree , notice the orange triangle ImageViewnext to the . If you hover your pointer over this triangle, you'll see a tooltip that warns you about the image's missing "contentDescription" attribute. Content descriptions help you define the purpose of UI elements, making your app easier to use in TalkBack.

However, adding pictures to this app is for decoration only. So instead of setting a content description that will be announced to the user, you can just set its importantForAccessibility property to no and let TalkBack skip ImageViewit .

  1. In the Component Tree , select ImageView.
  2. In the All Attributes section of the Attributes window , find importantForAccessibility and set it to no . The orange triangle next to it will disappear.ImageView
  3. Run the app again to see if it still works correctly.

Congratulations! You've added images to the Happy Birthday app, adjusted them to the accessibility guidelines, and made the app easier to translate into other languages!

insert image description here

5. Solution code

The solution code for the Happy Birthday app has been uploaded to GitHub, so if you want to see the code we ended up using, you can check it out.

GitHub is a service for developers to manage the code for their software projects. The service uses Git, a version control system that tracks changes made to each version of code. If you've seen the Google Docs version history, you can see what changes were made to the document and when it was done in the past. In the same way, you can track the version records of the code in the project. This is useful whether you are working on a project as an individual or as a team.

GitHub also has a website where you can view and manage your own projects. You can browse the Happy Birthday project files online at the GitHub link below, or download them to your computer.

Solution code URL: https://github.com/google-developer-training/android-basics-kotlin-birthday-card-with-image-app-solution

To get the code for this article and open it in Android Studio, do the following.

get code

  1. Click on the URL provided. At this point, the project's GitHub page opens in your browser.
  2. On the project's GitHub page, click the Code button to open a dialog.

insert image description here

  1. In the dialog, click the Download ZIP button to save the project to your computer. Wait for the download to complete.
  2. Locate the file on your computer (probably in the Downloads folder).
  3. Double-click the ZIP file to extract it. A new folder will be created containing the project files.

Open the project in Android Studio

  1. Start Android Studio.
  2. In the Welcome to Android Studio window, click Open an existing Android Studio project .

insert image description here

Note: If Android Studio is already open, select the File > New > Import Project menu option.

insert image description here

  1. In the Import Project dialog, go to where the unzipped project folder is located (probably in the Downloads folder).
  2. In the project folder, select the Happy Birthday folder.
  3. Click "Open".
  4. Wait for Android Studio to open the project.
  5. Click the Run button to build and run the application. Make sure the app builds as expected.
  6. Browse the project file in the Project tool window to see how your app is set up.

6. Summary

  • The Resource Manager in Android Studio helps you add and organize images and other resources.
  • ImageViewIs the interface element that displays images in the application.
  • ImageViewsA description of the content should be included to improve the accessibility of the app.
  • Text displayed to the user, such as a birthday greeting, should be extracted into a string resource to make it easier to translate the app into other languages.

7. Learn more

"Kotlin Development Basics for Android" related vocabularyResource Manager accessibility in
Android StudioSupports different languagesGet started with GitHub
[ImageView]


Eight, self-practice

Note: Contact is optional. You can take this opportunity to practice what you have learned in this article.

Do the following exercises:

  1. Create your own birthday card app with your design.
  2. First think about which ones you will need Views.
  3. In what order is it easiest to add them?
  4. What pictures do you need to add to the drawables folder?

Two types of bitmap images, JPEG files and PNG files, are usually used in Android applications. PNG files can contain transparent (blank) areas. For more information on image formats, see the reference for developers .

  1. Be sure to use constraints and margins to place Viewsbefore styling it.
  2. To make text stand out more on some images, try shadowColor, shadowDx, shadowDy and shadowRadius .

insert image description here

Check your works:

Your finished app should function correctly (without errors) and showcase the birthday card you designed.

Congratulations, you've created your own Birthday Card app!

Next: 【Classes and Object Instances in Kotlin】

Guess you like

Origin blog.csdn.net/Jasonhso/article/details/125948298