12 Tips Every Beginner Android Developer Should Know

12 Tips Every Beginner Android Developer Should Know

[[207924]]

Learn Android better one skill at a time

It’s been 12 years since Andy Rubin and his team set out to develop an operating system that would revolutionize the way mobile phones work, potentially making cell phones or smartphones a whole new experience for consumers and software developers. Previous smartphones were limited to texting and email (and of course making calls), which limited users and developers.

Android, as a system that breaks this shackle, has a very good framework design, providing everyone with not only a limited set of functions, but also free exploration. Some people would say that the iPhone is the disruptive product in the mobile phone industry, but we are not talking about how cool the iPhone is (or how expensive it is, right?), it still has limitations, which is something we never want.

However, as Uncle Ben said, with great power comes great responsibility, and we also need to take the design of Android applications more seriously. I have seen many tutorials that ignore this concept to beginners, and fully understand the system architecture before getting started. They just throw a bunch of concepts and codes at the readers without explaining the related pros and cons, their impact on the system, and what to use and what not to use.

In this article, we will introduce some tips that beginners and intermediate developers should master to better understand the Android framework. We will write more articles about practical tips in this series later. Let's get started.

1. The difference between @+id and @id

To access a graphical control (or component) in Java code, or to make it a dependency of other controls, we need a *** value to reference it. This *** value is defined with the android:id attribute, which essentially appends the user-provided id to @+id/ and writes it to the id resource file for use by other controls. The id of a Toolbar can be defined like this:

  1. android:id= "@+id/toolbar"  

This id value can then be identified by findViewById(…), which will look for the id in the resource file or directly reference it from the R.id path, and then return the type of the View being found.

The other method, @id, behaves the same as findViewById(…) - it will also find a component based on the provided id, but is limited to layout. It is generally used to arrange related controls.

  1. android:layout_below= "@id/toolbar"  

2. Use @string resource to provide string for XML

Simply put, don't use strings directly in XML. The reason is simple. When we use strings directly in XML, we usually use the same string again in other places. Imagine the nightmare when we need to adjust the same string in different places, but if we use string resources, we only need to change one place. Another benefit is that using resource files can provide multi-language support because corresponding string resource files can be created for different languages.

  1. android:text= "My Awesome Application"  

When you use strings directly, you will receive a warning in Android Studio, prompting you to change the hard-coded strings to string resources. You can click this prompt and press ALT + ENTER to open the string editor. You can also directly open the strings.xml file in the values ​​directory under the res directory and declare a string resource as follows.

  1. <string name = "app_name" >My Awesome Application</string>

Then use it to replace the hard-coded string,

  1. android:text= "@string/app_name"  

3. Use @android and ?attr constants

Try to use system-defined constants instead of re-declaring them. For example, there are several places in the layout that need to use white or #ffffff color values. Instead of using the #ffffff value directly every time, and don't re-declare resources for white yourself, we can use this directly.

  1. @android:color/white

Android predefines many commonly used color constants, such as white, black or pink. The most classic application scenario is transparent color:

  1. @android:color/transparent

Another way to reference constants is ?attr, which is used to assign predefined attribute values ​​to different attributes. Take a custom Toolbar as an example. This Toolbar needs to define width and height. The width can usually be set to MATCH_PARENT, but what about the height? Most of us don't pay attention to design guidelines and simply set a value that looks similar. This is wrong. You should not customize the height casually, but do this,

  1. android:layout_height= "?attr/actionBarSize"  

Another application of ?attr is to draw a water ripple effect when clicking on a view. SelectableItemBackground is a predefined drawable that can be set as the background of any view that needs to add a ripple effect:

  1. android:background= "?attr/selectableItemBackground"  

You can also use this:

  1. android:background= "?attr/selectableItemBackgroundBorderless"  

To display borderless ripples.

4. The difference between SP and DP

While there is no essential difference between the two, it is important to know what they are and where to use each.

SP means scale independent pixels, which is generally recommended for TextView. First, the text will not be displayed differently due to different display densities. In addition, the content of TextView needs to be stretched according to user settings, or only the font size needs to be adjusted.

In other places where you need to define the size and position, you can use DP, which is density-independent pixels. As mentioned before, DP and SP have the same nature, but DP will automatically stretch according to the display density, because the Android system will dynamically calculate the actual displayed pixels, so that components using DP can have the same display effect on devices with different display densities.

5. Application of Drawable and Mipmap

The two most confusing things are - how much difference is there between drawable and mipmap?

Although these two seem to have the same purpose, they are designed for different purposes. Mipmap is used to store icons, while drawable is used for any other format. We can see why they cannot be mixed by looking at how they are used internally by the system.

You can see that there are several mipmap and drawable directories in your application, each representing a different display resolution. When the system reads resources from the drawable directory, it only selects a certain directory based on the display density of the current device. However, when reading mipmaps, the system will select the appropriate directory based on needs, not limited to the current display density, mainly because some launchers will deliberately display larger icons, so the system will use larger resolution resources.

In short, using mipmap to store icons or marker images allows you to see resolution changes on devices with different display densities, while other image resources that are displayed as needed use drawable.

For example, the display resolution of Nexus 5 is xxhdpi. When we put the icon in the mipmap directory, all mipmap directories will be read into memory. If we put it in drawable, only the drawable-xxhdpi directory will be read, and other directories will be ignored.

6. Use vector graphics

In order to support screens with different display densities, it is a common trick to add multiple versions (sizes) of the same resource to the project. This approach is indeed useful, but it also brings certain performance costs, such as larger apk files and additional development work. In order to eliminate this effect, Google's Android team released new vector graphics.

Vector graphics are SVG (Stretchable Vector Graphics) described in XML. They are drawn with a combination of points, lines, curves and fill colors. Because vector graphics are drawn dynamically with points and lines, they can be stretched at different display densities without losing resolution. Another benefit of vector graphics is that they are easier to animate. You can animate by adding multiple vector graphics to an AnimatedVectorDrawable file, instead of adding multiple images and processing them separately.

  1. <vector xmlns:android= "http://schemas.android.com/apk/res/android"  
  2. android:width= "24dp"   
  3. android:height= "24dp"   
  4. android:viewportWidth= "24.0"   
  5. android:viewportHeight= "24.0" >
  6. <path android:fillColor= "#69cdff" android:pathData= "M3,18h18v-2L3,16v2zM3,13h18v-2L3,11v2zM3,6v2h18L21,6L3,6z" />
  7. </vector>

The above vector definition can draw the following figure,

[[207925]]

To add vector graphics to your Android project, right-click on the app module in your project and select New >> Vector Assets. This will open the Assets Studio, where you can add vector graphics in two ways: one is to select from Material icons, and the other is to select a local SVG or PSD file.

Google recommends using Material icons for all apps to maintain the consistency and unified experience of Android. Here are all the icons, remember to take a look.

7. Set the beginning and end of your boundaries

This is one of the most overlooked areas. Margins! Adding margins is easy, but what if you want to support older platforms?

The "start" and "end" of borders are supersets of "left" and "right" respectively, so if the app's minSdkVersion is 17 or lower, the "start" and "end" definitions of borders and padding are what the old "left"/"right" definitions require. On systems that don't define "start" and "end", these two definitions can be safely ignored. You can declare it like this:

  1. android:layout_marginEnd= "20dp"
  2. android:paddingStart= "20dp"  

8. Use the Getter/Setter Generation Tool

One annoying thing when creating a container class (just to simply hold some variable data) is to write multiple getters and setters, copy/paste the body of the method and rename it for each variable.

Fortunately, Android Studio has a solution. To do this, declare all the variables you need in your class, then open Toolbar >> Code. The shortcut is ALT + Insert. Clicking Code will bring up Generate, which will bring up a lot of options, including Getter and Setter options. Keep the focus on your class page and click, and all getters and setters will be added to the current class (you can go back to the previous window if needed). Pretty cool, right?

9. Use Override/Implement Generator

This is another very useful generation tool. It is easy to customize a class and then extend it, but what if you want to extend a class you are not familiar with? For example, if you want to use ViewPager to display some pages, you need to customize a PagerAdapter and implement its overload methods. But what are the specific methods? Android Studio is very considerate and forcibly adds a constructor for the custom class, or you can use the shortcut key (ALT + Enter), but other (virtual) methods in the parent class PagerAdapter need to be added manually, which I guess most people find annoying.

To list all the methods that can be overridden, click Code >> Generate and Override methods or Implement methods, depending on your needs. You can also select multiple methods for your class, just hold down Ctrl while selecting the methods and then click OK.

10. Understand Context Correctly

Context is a bit scary, and I guess many beginners never really understand the structure of the Context class - what it is and why it is used everywhere.

Simply put, it brings together everything you can see on the screen. All views (or their extensions) are bound to the current environment through Context. Context is used to manage application-level resources, such as display density, or the current associated activity. Activities, services, and applications all implement the interface of the Context class to provide internal resources to other associated components. Take the example of a TextView added to MainActivity. You should have noticed that when creating an object, the constructor of TextView requires a Context parameter. This is to obtain the resources defined in TextView. For example, TextView needs to use the Roboto font internally. In this case, TextView needs Context. And when we pass Context (or this) to TextView, we are telling it to bind to the lifecycle of the current activity.

Another key application of Context is to initialize application-level operations, such as initializing a library. The life cycle of a library is independent of the application, so it needs to be initialized with getApplicationContext() instead of getContext or this or getActivity(). It is very important to master the correct use of different Context types to avoid memory leaks. In addition, Context is used to start an activity or service. Remember startActivity(…)? When you need to switch activities in a non-activity class, you need a Context object to call the startActivity method because it is a method of the Context class, not the Activity class.

  1. getContext().startActivity(getContext(), SecondActivity.class);

If you want to learn more about Context's behavior, you can have a look here or here. The first is a good article about Context and where to use it. The other is Android's documentation on Context, which fully describes all its features - methods, static flags and more.

Bonus #1: Formatting Code

Who doesn't like neat, uniformly formatted code? Well, almost every one of us, when writing a class with more than 1000 lines, hopes that our code can have a proper structure. Moreover, it is not only the large classes that need formatting, but every small module class also needs to keep the code readable.

With Android Studio, or any JetBrains IDE, you don't need to manually organize your code, like adding indents or spaces before =. Just write the code the way you want, and when you want to format it, press ALT + CTRL + L on Windows or ALT + CTRL + SHIFT + L on Linux. The code will be automatically formatted.

Bonus #2: Using Libraries

An important principle of object-oriented programming is to increase code reusability, or to reduce the habit of reinventing the wheel. Many beginners follow this principle incorrectly. This path has two directions,

  • No libraries are used, write all the code yourself.
  • Use libraries to handle everything.

No matter which direction you go in, it is wrong. If you choose the first direction completely, you will consume a lot of resources just to satisfy your pride of owning everything. It is very likely that your code has not been tested as much as the alternative library, which increases the possibility of module problems. If resources are limited, don't reinvent the wheel. Use a tested library directly, and when you have a clear goal and sufficient resources, you can replace this library with your own reliable code.

Going in the other direction is more problematic - the reliability of someone else's code. Don't get used to relying on someone else's code for everything. Try to write your own code when you don't have too many resources or you have control over it. You don't need to use a library to create a custom TypeFaces (font), you can write one yourself.

So remember to strike a balance between these two extremes - don't reinvent everything, and don't rely too much on external code. Stay neutral and write code according to your own abilities.

This article was originally published on What's That Lambda. Visit the website to read more similar articles about Android, Node.js, Angular.js, and more.

<<:  [Special Topic] The 10th issue of the Aiti Tribe Technical Clinic: How to learn Python? The method is very important

>>:  5 Tips to Make Your Mobile User Experience Stand Out

Recommend

The tent is made of 100 tiger skins, the only one of its kind in the world

In the Ganzi Tibetan Autonomous Prefecture Museum...

"Grave Robbers' Chronicles": The first shot in the video website's comeback?

After continuing to burn money and suffer losses ...

One article thoroughly grasps the essence of community operation

The topic of community operation is an over-mytho...

Marketing promotion: Why is product promotion ineffective?

When users are faced with product marketing that ...

Keep brand marketing promotion model!

In recent years, I have found that vertical Inter...

From 0 to 1 million users, what operations need to do!

Let me introduce myself first. Before last year, ...

7 essential promotion skills for operators! Did you know?

01 Promotion skills For operations personnel, whe...

Alibaba B-side case! Cainiao Intelligent Design Middle Platform Design Review

Before we start this topic, we need to have a bas...

Can the godlike NVIDIA lead the way for TV gaming?

After PC, the next gaming battlefield for domesti...

Look! There's a slippery "wireless mouse" in the desert

Today's species is very suitable for playing ...

Kuaishou live streaming sales cases for maternal and infant products

Live streaming e-commerce has become a new growth...