Lesson 8. Working with screen elements from the code

Lesson 8. Working with screen elements from the code


In this lesson we:

– learn how to handle code on View-elements on the screen and change their properties

Let’s create a project:

Project name: P0081_ViewById
Build Target: Android 2.3.3
Application name: ViewById
Package name: ru.startandroid.develop.viewbyid
Create Activity: MainActivity

To access the screen element from the code, we need it ID. It is prescribed or in Properties, Or d layout filesas you see fit. There is a clear format for ID – @ + Id / name, where + means it is a new resource and should be added to R.java class, if it does not already exist.

Let’s open it main.xml, for TextView let’s say ID = @ + id / myText and save

now open R.java and we see that for the class id a constant appeared myText. That is, to address it, it is necessary to write R.id.myText.

It is associated with a TextView element and we can use it to access the element programmatically. To do this, we need the findViewById method. It returns the View ID. Let’s write a call to this method. Let me remind you that while we are writing our code in method onCreate. This is the method that is called when creating an Activity. If it’s suddenly unclear where to write, you can peek at the end of the lesson, that’s where I posted the code.

Open MainActivity.java after the method call string setContentView write:

View myTextView = findViewById(R.id.myText);

If View is highlighted in red, then most likely this class is added to the import section. Press CTRL + SHIFT + O to automatically import again.

now myTextView (View Type) is our on-screen TextView. But the View type is the ancestor of TextView (and other View elements). And it does not suit us if we want to perform operations corresponding to TextView. So we need to convert View to TextView. Let’s change our code to the following:

TextView myTextView = (TextView) findViewById(R.id.myText);

now myTextView has type TextView, And the result of the findViewById method will be converted from View to TextView. Now we can apply the TextView class methods to myTextView. Take the setText method as an example. The text = is now displayed Hello World, MainActivity!. We will programmatically change it to New text and TextView

myTextView.setText("New text in TextView");

Save, run (CTRL + F11) and see that the text has changed

Add the button (Button) to the screen, Id = @ + id / myBtn, leave the text as default. Save – CTRL + SHIFT + S (if not saved, R.java may not display an ID).

We write the code:

Button myBtn = (Button) findViewById(R.id.myBtn);

Note that I have the same object name and ID

They do not interfere with each other and do so even more logically. This is at your discretion. Yes, we found the button, now let’s change its text:

myBtn.setText("My button");

Let’s start the program. The text on the button has changed, you can press the button, but nothing will happen. Because we did not specify anywhere what to do when pressed. Let’s deal with this in the next lesson. In the meantime, let’s make the button inactive.

myBtn.setEnabled(false);

We changed the parameter Enabled. You can now press the button. Let’s save, run and make sure.

Add CheckBox, id = @ + id / myChb. By default, the checkmark is not worth it. Let’s put it programmatically, using the setChecked method, which changes the Checked parameter.

CheckBox myChb = (CheckBox) findViewById(R.id.myChb);
myChb.setChecked(true);

When we launch the application, we see that the code has worked.

As you can see, everything is easy. we use the method findViewByIdTo by ID get an object matching some View-element (Button, TextView, CheckBox) and then call the required object methods (setText, setEnabled, setChecked).

The result should be:

package ru.startandroid.develop.viewbyid;
import android.app.Activity;
import android.os.Bundle;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.TextView;

public class MainActivity extends Activity {
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);
        
        TextView myTextView = (TextView) findViewById(R.id.myText);
        myTextView.setText("New text in TextView");
        
        Button myBtn = (Button) findViewById(R.id.myBtn);
        myBtn.setText("My button");
        myBtn.setEnabled(false);
        
        CheckBox myChb = (CheckBox) findViewById(R.id.myChb);
        myChb.setChecked(true);
    }
}

In the next lesson:

– Learn how to handle the push of a button




Discuss in the forum [257 replies]

Lesson 7. Layout options for View items.

Lesson 7. Layout options for View items.


In this lesson we:

– We understand the characteristics of the screen
– consider layout parameters (height, width, indentation, gravity, weight)

screens

First, a little theory on the screens. The screen has such physical characteristics as diagonal and resolution. The diagonal is the distance between opposite corners of the screen, usually measured in inches. Resolution – The number of horizontal and vertical points that the screen is capable of displaying is measured in pixels.

Take the HTC Desire smartphone screen as an example. Diagonal = 3.7 inches, resolution = 800×480 pixels.

The number of pixels in one inch is called dpi (dot per inch). Let’s find out why dpi is equal in this case, remembering the classics: c2 = a2 + b2, Where c is the number of pixels diagonally, ie, accommodates 3.7 inches. a and b are the sides of the screen.

c = 3.7 * dpi
(3.7 * dpi)2 = 4802 +8002
dpi2 = 870400 / 13.69 = 63579
dpi = 252. That is, one inch of the screen holds a row of 252 pixels.

Let’s return to the topic of the lesson. Consider in detail the following options for View items

Layout width and Layout height

We already talked about width (layout_width) and height (layout_height) in the last lesson. We can specify absolute values ​​for them, and we can use constants. Let’s take a closer look at these possibilities.

Absolute values:

The following units of measurement (OI) are used:

dp or dipl – Density-independent Pixels. Abstract AI that allows applications to look the same on different screens and resolutions.

sp – Scale-independent Pixels. The same as dp, only used for font sizes in View elements

pt – 1/72 inches, determined by the physical size of the screen. This OI is from the printing press.

px – pixel, it is not recommended to use so the application will look different on different screens.

mm – millimeter, is determined by the physical size of the screen

and – inch, is determined by the physical size of the screen

You can read more about the differences and relationships between these AIs in this site material.

constants

match_parent (fill_parent) – means that the element will occupy all the width / height available to it in the parent element.

wrap_content – the width / height of the element will be determined by its content

Let’s create a project:

Project name: P0072_LayoutProp
Build Target: Android 2.3.3
Application name: LayoutProp
Package name: ru.startandroid.develop.layoutprop
Create Activity: MainActivity

open main.xml. customize the root LinearLayout to horizontal orientation, remove TextView, And add Button with width and height equal wrap_content. It is displayed on the screen and its width corresponds to the text on it.

Change the text from “Button” to “Button with text”, save and look at the screen.

Button has become wider because width is determined by content. If we now explicitly specify a width of 250 dp, the button will be expanded regardless of the content.

Now let’s make the width even match_parent. Button stretched out on everything the width of the fatherThat is LinearLayout. And LinearLayout, in turn, will take up the entire width of the screen.

If our father has multiple items and we want them to take up space, we need to use the parameter Layout weight. The free space is distributed between the elements in proportion to their weight values.

Let’s change the text of our button to B1 and add a LinearLayout neighbor – the second button with text B2. Set the width for both wrap_content

Let’s deal with separation. If we want the buttons to share the space of the father equally – then for both we specify weight = 1. In this case, the buttons are even in width.

Note that no units are used, they are simply numbers.

If you want B1 to occupy a quarter, and B2 three quarters of the free space, then put weight = 1 for B1 and weight = 3 for B2.

The number of elements can be any. Add a button with the text B3, weight = 2 and width = Wrap_content.

received screen xml code:



    
    
    

now for B2 and B3 specify weight = 0. They no longer claim free space and occupy the width of the content as well B1 takes away everything.

Of course, all of the above can be applied to the height parameter – height.

When used weight you can specify a value height or width = 0dp. In this case, the content of the elements will not be taken into account and the result will be more appropriate for the weight coefficients.

Layout gravity

The layout_gravity parameter is similar to an alignment with Word or Excel. It is most convenient to demonstrate it using FrameLayout. I did not describe this Layout in the last lesson because it is quite simple. By default, he places all the elements he places in the upper left corner and does not build them in any way. For us, this is very suitable for demonstrating alignment settings.

let’s create grlayout.xml:



    
        
        
        
        
        
    

The screen shows:

For clarity, the button’s text reflects its properties. Everything is obvious and simple.

I honestly tried to understand why gravity values ​​were needed fill_ * and clip_ *, But I never understood. What is written about them in help does not work for me. If you have information about this – write in the comments.

Layout margin

The margin options are completely similar margin with html. This is a retreat. It can be on all sides at once, or only on the necessary sides. Let us demonstrate this by the example of TableLayout. let’s create marginlayout.xml and draw a three-by-three table with buttons.



    
        
            
            
            
        
        
            
            
            
        
        
            
            
            
        
    

And on the button in the center we will experiment.

margin = 50 dp
Around the button on each side, an indent = 50 dp.

margin left = 10 dp
margin top = 20 dp
Indent left and top.

margin right = 30 dp
margin bottom = 40 dp
Indent on the right and bottom.

The lesson came out great, but useful. I think this was the last lesson in design, modeling and layout and we will start to code.

style

If anyone has used HTML, they must have heard about cascading style sheets – CSS. Styles allow you to group attributes of elements (buttons, tables, paragraphs, etc.). Next, you simply apply to style elements, and the element is drawn with all the style attributes in mind. And there is no need to repeat the same code several times for the elements that should look the same. This is especially useful when changing attributes. You just change the style once and all the elements with that style change.

Android also has styles and they have exactly the same purpose. If you have multiple elements and you want them to look the same, then you simply create one style and apply it to the desired elements. Basically, you can still not bother about it and start using styles when you get experience. Well, to those who are interested in it right now – I ask in this thread of our forum. The icamys user for example explains in detail how to use styles.

In the next lesson:

– learn how to access View-elements from the code and change their properties




Discuss in the forum [103 replies]

Lesson 6. Types of Layouts. Key differences and properties.

Lesson 6. Types of Layouts. Key differences and properties.


The location of the View items on the screen depends on ViewGroup (Layout) in which they are. In this lesson, we will cover the main types Layout.

LinearLayout – Displays View items as a single row (if Horizontal) or a single column (if it is Vertical) I used this in the past lesson when demonstrating the use of layout files when changing orientation.

TableLayout – Displays table, row and column items.

RelativeLayout – for each element, its position relative to the other elements is adjusted.

AbsoluteLayout – for each element, an explicit position on the screen in the coordinate system (x, y) is indicated

Consider these types

LinearLayout (LL)

This kind of ViewGroup is offered by default when creating new layout files. It is really comfortable and flexible enough to create screens of varying complexity. LL has an Orientation property that determines how the child elements will be positioned – horizontal or vertical.

Let’s make a simple and clear example.

Create a project:

Project name: P0061_Layouts
Build Target: Android 2.3.3
Application name: Layouts
Package name: ru.startandroid.develop.layouts
Create Activity: MainActivity

Open the layout file main.xml, And put the following code in it:



Now the root element we have is LinearLayout with vertical orientation.

Drag the left button in the LinearLayout root three buttons. They were lined up vertically.

Now in Properties we change the property for LL Orientation on horizontal and save (CTRL + SHIFT + S) – the buttons are lined up horizontally.

GroupView can be invested in each other. We will put two others in one LL. Delete all items (three buttons) in main.xml except the root LL. Specify the root LL orientation vertically and add two new horizontal LLs to it. In the list of items on the left, they are in the Layouts section. I remind you that you can drag items from the list not only to the screen, but also to a specific item in the Outline tab.

Add three buttons to each horizontal LL. There are two horizontal row of buttons. Make sure that in horizontal LinearLayout, height is set to wrap_content.

TableLayout (TL)

TL consists of strings TableRow (TR). Each TR, in turn, contains View-elements that form columns. That is, the View count in TR is the number of columns. But the number of columns in the table must be equal for all rows. Therefore, if different TRs have different number of View elements (columns), then the total number is determined by TR with the maximum number. Consider the example.

Let’s create a layout file tlayout.xml. with the TableLayout root element

Add three TableRow rows (from the Layouts section on the left) in the TableLayout root and add two buttons to each row. The result: our table has three rows and two columns.

Add a couple more buttons to the first line. The number of columns for all rows is now 4 because it is determined by the row with the maximum number of elements, that is, the first row. For the second and third rows, the third and fourth columns are simply blank.

In the second line we add TextView and Button, and we will make the text in the added TextView blank. In the third line, do the same. We see that these elements fit into the third and fourth columns. And so TextView we have no text and the screen is not visible, it seems that the third column in the second and third row is empty.

The width of a column is determined by the widest element from that column. Let’s enter the text into one of the TextView and see that it has expanded the column.

I will remove the elements of the fourth column and build such a screen. Try to do the same as exercise.

TL can contain not only TR but also normal View. For example, add Button directly to TL, not TR, and you’ll see that it stretches the width of the entire table.

RelativeLayout (RL)

In this Layout view, each View element can be positioned in a certain way relative to the specified View element.

Types of relationships:

1) left, right, top, bottom of the specified element (layout_toLeftOf, layout_toRightOf, layout_above, layout_below)

2) aligned on the left, right, top, bottom edge of the specified element (layout_alignLeft, layout_alignRight, layout_alignTop, layout_alignBottom)

3) is aligned on the left, right, top, bottom edge of the parent (layout_alignParentLeft, layout_alignParentRight, layout_alignParentTop, layout_alignParentBottom)

4) aligned centered vertically, centered horizontally, centered vertically, and horizontally relative to the parent (layout_centerVertical, layout_centerHorizontal, layout_centerInParent)

You can read in detail in help.

let’s create rlayout.xml and copy the following xml code there:



    
    
    
    
    
    

Here we have the root element – RelativeLayout.

The following screen was displayed:

We are interested in xml code. I will briefly describe unfamiliar attributes and their meanings:

android: layout_width=“Match_parent”
android: layout_height=“Wrap_content”
android: id=“@ + Id / entry”

– word android in the name of each attribute is namespace, I will omit it for explanations.
– id is the element ID,
– layout_width (Element width) and layout_height (Element Height) can be specified in absolute values, and can be as follows: fill_parent (The maximum width or height possible within one parent) and wrap_content (Width or height is determined by the content of the element). The help indicates that there is more match_parent. This is the same as fill_parent. For some reason, the developers of the system decided that the name match_parent is more convenient and will gradually abandon fill_parent. In the meantime, it was left for compatibility. So remember that match_parent = fill_parent and in the future we will try to use match_parent. We will dwell on this later and explore in more detail.

Now back to our elements. In the example we see TextView, EditText and two Button – OK and Cancel. Let’s take a closer look at the attributes we are interested in.

TextView
android: id=“@ + Id / label” – ID
android: layout_width=“Match_parent” – occupies all the width available to it (though it is not visible on the screen);
android: layout_height=“Wrap_content” – height in content;
does not belong to anything

EditText
android: id=“@ + Id / entry” – ID
android: layout_width=“Match_parent” – all width available to him
android: layout_height=“Wrap_content” – height in content
android: layout_below=“@ + Id / label” – located lower TextView (ID link)

Button_OK
android: id=“@ + Id / ok” – ID
android: layout_width=“Wrap_content” – width in content
android: layout_height=“Wrap_content” – height in content
android: layout_below=“@ + Id / entry” – located below EditText
android: layout_alignParentRight=“True”aligned to the right edge of the parent
android: layout_marginLeft=“10dip” – has an indent on the left (so that Button_Cancel is not tight)

Button_Cancel
android: layout_width=“Wrap_content” – width in content
android: layout_height=“Wrap_content” – height in content
android: layout_toLeftOf=“@ + Id / ok” – located left by Button_OK
android: layout_alignTop=“@ + Id / ok”aligned on the top edge Button_OK

You can add elements and experiment with their placement.

Note that the View item may not have an ID (android: id). For example, TextView is not usually needed because they are mostly static and we almost never access them when running the program. Another thing is EditText – we work with the contents of the text box, and Button – we need to handle the click and accordingly know which button is pressed. In the future, we will see another need to specify an ID for the View element.

AbsoluteLayout (AL)

Provides absolute positioning of elements on the screen. You specify the coordinates for the upper left corner of the component.

let’s create alayout.xml with the AbsoluteLayout root

Now try dragging different elements to the screen. They don’t line up like LinearLayout or TableLayout, but lie where you dragged them. That is absolute positioning.

We open the xml code and see that they are used to specify the coordinates layout_x and layout_y.



    
    
    
    
    
    
    

At first, it seems to be the most convenient and intuitive way to position the elements on the screen – they are immediately located where you need them. But this is only when you are designing for a screen with a specific resolution. If you open the application on another screen, all the items will move and it will not work out as you planned. Therefore, this Layout is not recommended for use. And its compatibility with future versions of Android is not guaranteed.

There are many more species of ViewGroup, and we will gradually master them. Until we have enough of these.

In this lesson we:

Considered the main types of Layout: LinearLayout, TableLayout, RelativeLayout, AbsoluteLayout

In the next lesson:

Let’s take a look at some of the Layout properties of View items that allow you to customize their layout in ViewGroup.




Discuss in the forum [98 replies]

Lesson 5. Activity Layout File. XML representation. Change screen orientation.

Lesson 5. Activity Layout File. XML representation. Change screen orientation.


In the last lesson, we learned that Activity reads the layout file and displays what is configured in it. Now let’s find out where Activity knows which layout file to read.

The lesson was updated on 2/02/2015

Let’s create an application for this lesson. To do this, you need to create a module in the Android lessons project. We created this project in the past lessons. If you have not yet learned how to create modules, you can revisit Lessons 3 and 4.

And let’s take a moment to look at it. The following lessons were written a long time ago and were written under the Eclipse development environment. Accordingly, all lessons contain information for creating a project in Eclipse.

But Eclipse is different from Android Studio in organizing projects / modules. And now we will understand how to use project creation information in Eclipse when creating modules in Android Studio.

The project creation info for Eclipse looks like this:

Project name: P0051_LayoutFiles
Build Target: Android 2.2
Application name: LayoutFiles
Package name: ru.startandroid.develop.LayoutFiles
Create Activity: MainActivity

Typically, this is the text at the beginning of each lesson.

And to create a module in Android Studio, we need information like this

Application / Library name: LayoutFiles
Module name: p0051layoutfiles
Package name: ru.startandroid.p0051layoutfiles

How to get new from old? Consider the example of this lesson. Let’s take values ​​for Eclipse and replace them in Android Studio.

for the field Application/Library name you take value Application name, Without any changes. That is LayoutFiles.

for Module name you can take values Project name, But capitalization should be lowercase and lower underscores should be deleted. That is, with P0051_LayoutFiles we get p0051layoutfiles.

Package name is it ru.startandroid. plc just received Module nameThat is, startartroid.p0051layoutfiles

Use this diagram in all of the following lessons to create modules.

Also, information for Eclipse has a field Create Activity. We will use it when creating the module, when we specify the name Activity, in the field Activity Name

You need to substitute a value with Create Activity. This is usually always MainActivity.

Remember these instructions and apply each lesson to create modules.

Let’s go back to the lesson.

In development, each Activity is mapped to the java class (the heir to the android.app.Activity class). When running the program, when the system must show Activity and continue to work with it, it will call methods of this class. And what we do in these methods depends on the behavior of Activity.

When creating the module, we indicated that we needed to create an Activity named MainActivity

We asked to create an Activity, and the development environment created a class for us (in the future we will learn to create them ourselves).

Let’s look at this class: double-click the file: java en startandroid p0051layoutfiles MainActivity.java

We look at the java code. We are interested in the method onCreate – it is invoked when an application creates and displays Activity (other methods are not yet addressed). Let’s see the onCreate implementation code.

The first line:

super.onCreate(savedInstanceState);

it is a call to the parent class method that performs the necessary procedures, we do not touch it.

We are now very interested in the following line:

setContentView(R.layout.activity_main);

SetContentView (int) method – sets the Activity content of the layout file. But as an argument, we do not specify the path to the layout file (res / layout / activity_main.xml) but the constant, which is the file ID. This constant is generated automatically in the R.java file, which we will not touch yet. This class will store the generated ID for all project resources (from the res / * folder) so that we can access them. The names of these ID constants match the names of the resource files (without extensions).

The res / layout / activity_main.xml file was created by the development environment along with Activity. Its name was required on the same screen as the name Activity (screen above).

In the following lessons, this file is usually called main.xml, not activity_main.xml

Double-click res / layout / activity_main.xml

let’s see what’s out there

Let’s launch the application and see what it shows us

That’s right – Activity mirrored what activity_main.xml says.

Let’s try to display the contents of another file. Let’s create another layout file, for example myscreen.xml. To do this, select the res / layout folder in our module and right-click on it. Select New> Layout resource file from the menu. For hotkey lovers, there is a more convenient way: with the res / layout folder selected, press ALT + Insert, and there is already Enter at Layout resource file.

the window opens

Enter the name of the file myscreen, the rest until we change, click OK.

A new myscreen.xml file should appear in the layout folder

This new layout file should open immediately for editing. Add a Plain TextView element from the list to the left and use Properties to change its text to: “new layout file myscreen for activity”.

We must save (CTRL + S).

When creating a new myscreen layout file, Wednesday added a new constant for this file, R.layout.myscreen, to R.java. And now we will be able to point to this new layout file through this constant.

We configure Activity to use the new myscreen.xml file, not the activity_main.xml that was originally. Open MainActivity.java and override the setContentView method argument. Replace “R.layout.activity_main” with “R.layout.myscreen” (ID of the new layout file). It should turn out like this:

  @Override
  protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.myscreen);
  }

Save the code (CTRL + S) and run the application (SHIFT + F10).

Now we will be asked to confirm that we want to run the application on the included emulator.

To prevent it from being asked every time, turn on the Use same device for future launches checkbox and click OK.

application started

We see that it now displays content from myscreen.xml because we explicitly specified it in the setContentView method that is executed when creating (onCreate) Activity

Layout file in XML format

When you open an activity_main or myscreen file in Android Studio layout, you can see its visual representation. That is, some preview of what it will look like on the screen. Below you can see two tabs – Design and Text. Click the Text tab

We see a fairly readable xml description of all View our layout file. The names of the xml elements are the classes of the View elements, the xml attributes are the parameters of the View elements, that is, all those parameters that we change through the Properties tab. You can also make changes right here and the changes will be displayed in the Design tab. For example, let’s change the text in TextView. Instead of “new layout file myscreen for activity”, we write “some new text”

Save. Open Design and see changes.

Usually, the authors of the textbooks give the contents of layout-files exactly in xml form. This is convenient – you can simply copy a snippet and use it, and you don’t have to manually add View items, run around Properties, and customize everything with your hands. I will do the same in my projects.

Layout file when changing screen orientation

By default, we adjust the layout file to the vertical orientation of the screen. But what if we turned our smartphone back and the horizontal orientation turned on? Let’s watch.

Let’s change myscreen.xml. Add a vertical row of buttons and change the caption.

xml code (you can copy and replace the contents of your myscreen layout file in the Text tab):



    
    
    
        
        
        
        
    

Note – I added a vertical LinearLayout and put 4 buttons in it. Let’s discuss this in more detail in the next lesson.

Save the file, launch the application.

In vertical orientation, everything is approx.

Click in the CTRL + F12 emulator, the orientation has changed to horizontal and our buttons no longer fit into the screen.

That is, we need another layout file, which would be sharpened to a horizontal orientation and in our case would bring the buttons horizontally.

But how to let Activity know that it has to use one layout file in the vertical orientation and another in the horizontal orientation? The creators of Android have already thought about this for us. We have the ability to create a layout file that will be used by the application when the device is horizontally oriented.

Creating such a file is almost the same as creating a regular layout file. We get to the res / layout folder and create a new Layout resource file. The file name is the same as myscreen. It is necessary to add a specifier that will allow the application to understand that this layout file should be used in a horizontal orientation. To do this, find Orientation in the list of specifiers at the bottom left

And press the right arrow button. Thus, we have included the use of an orientation specifier. We need to point out that we are interested in a horizontal orientation: Landscape. Select this value from the list.

Note that the value of the Directory name field has changed

By specifying the specifier, we have specified that our new layout file will be created in the res / layout-land folder, not res / layout as usual. That is, the -land specifier indicates that the layout files in this folder will be used in the horizontal orientation of the device.

click OK

Let’s look at the structure of the module

We see that we now have two myscreen files: normal and land. You can see it in the folder structure. To do this, change the project view from Android to Project from above

And you will see that the module now has res / layout and res / layout-land folders. And both contain a myscreen file.

Double-click the res / layout-land / myscreen file and change its contents to the following xml code:



    
    
    
        
        
        
        
    

The Design tab will show the following:

In this layout file, we position the buttons horizontally so that they are properly displayed in a horizontal orientation.

Note the file name at the top. There is a land specifier there so you always understand which of the two myscreen you are currently editing.

Let’s start the program.

Activity reads the layout file we specified in the setContentView method, that is, myscreen.xml, and displays its contents. In doing so, it takes into account the orientation of the device, and in the case of horizontal orientation takes myscreen from the res / layout-land folder (if it exists, of course).

Let’s switch the CTRL + F12 orientation.

Activity understands that it is in vertical orientation and uses the myscreen layout file from the res / layout folder.

P.S.

A little more about the lessons. Next, in almost every lesson, the main layout file will be called main.xml. Don’t be discouraged, just remember that your primary file is activity_main.xml.




Discuss in the forum [367 replies]

Lesson 4. Screen components and their properties

Lesson 4. Screen components and their properties


Let’s see how in the Android applications is formed what we see on the screen.

Lesson updated 07/07/2017

If you draw an analogy with Windows, the application consists of windows called Activity. At one particular time, one Activity is usually displayed and occupies the entire screen, and the application switches between them. An example is the mail application. In it one Activity – the list of letters, another – viewing letters, the third – setting of a box. When you work, you move on them.

Activity content is formed from different components called View. The most common View is the Button, Input Box, Checkmark, etc.

This can be roughly depicted as:

It should be noted that View is usually hosted in ViewGroup. The most common example of ViewGroup is Layout. Layout is of different types and is responsible for how its child View will be located on the screen (table, row, column …)

Also, Android 3.0 has a new entity – Fragment. But we will cover the snippets in later lessons so that we do not complicate the matter now.

Probably already confused with new words and terms, let’s see it all in practice.

Let’s create a supplement to this lesson. To do this, run Android Studio and open the Android lessons project we created in the previous lesson. Most likely, this project will immediately open to you by default.

Let me remind you that we decided to create all the modules (applications) for lessons in this project. Instead of creating a separate project for each lesson.

Let’s create a module. In the menu File >New> New Module. All the steps are similar to what we did in the previous lesson, but there will be other program and module names

Application / Library name: BasicViews
Module name: p0041basicviews
Package name: ru.startandroid.p0041basicviews

module p0041basicviews created and visible in the list of modules on the left:

In this module we are interested in a file: really > layout > activity_main.xml

This is a layout file. In it, we define the set and location of the View components we want to see on the screen. At program startup, Activity reads this file and shows us what we have built. Most likely, you already have it open for editing, but just in case let’s re-open it with a double click and see how it looks.

A bunch of buttons, captions, etc. I noted important areas with numbers (1 to 6). Let’s walk through them

1) Design and Text

Desing is a graphical representation of the screen. It is now open. And Text is a text representation. It looks like this:

Little is known. For now, we will only use Design submissions.

2) Display modes

In the screenshot in area 3 you see two screens. Ordinary white and some blue next to it. It’s the same screen, but it’s displayed in two different modes:
Design – In it, we see the View components as they normally look on the screen.
Blueprint – Only the contours of the View components are displayed

The buttons in area 2 allow you to switch modes:
– Design
– Blueprint
– Design + Blueprint

I usually will use Design mode in the lessons. You can use whichever you prefer.

3) Screen

Here you can see what your application screen looks like. We will be adding different components from area 4 here.

4) The palette

This is a list of all View components that you can add to your screen: buttons, input boxes, checkboxes, progressbar and more.

5) Component tree

Here is a hierarchy of View components of your screen. Now, for example, the root element is ConstraintLayout. And it has TextView embedded.

6) Properties

This area is still empty. When working with any View component, the properties of that component will be displayed here. The properties allow you to customize the appearance, location and contents of the View component.

To understand what the following is about, please see this lesson:

Lesson 180. ConstraintLayout. foundations

Although it is numbered 180, it is simple and straightforward. In it you will learn how to add View components to the screen. After reading, come back here and we will continue.

Now that you know how to add components to the screen, we can continue.

Right now, we only have TextView on the screen. Let’s add some more components. For example, Button and CheckBox.

Set them some bindings so they don’t leave at startup.

Note that the components appeared in Component Tree

value button and checkBox are the IDs that were assigned to the components automatically. As long as we leave them as such, we will later learn to change them and make them more meaningful.

Now let’s change the captions on these components. In the Component Tree tab (left and bottom), click TextView to select this component.

Now we need the Properties tab (right). In the screenshot, it is marked as area 6. Here we can customize the properties of the component selected in the Component Tree (or on the screen).

Find the property tab in the Properties tab text. Now there is the text Hello World!, Which is displayed on the screen. Let’s change it to your text. Place your cursor in this field and type in, for example, “Google Android”.

I do not advise pressing this Enter box because the studio sometimes offers autocomplete, which may not be right for you. Therefore, after you have written your text there, just click anywhere on the component screen.

The text on the screen has changed. It was Hello World! Became Google Android.

Similarly, you can change the text on the button and the checkbox. Just select these components on the screen or in the Component Tree, in the Properties search for the text property and write your text there. You can even in Russian.

Everything you have configured in this screen will be saved in the res> layout> activity_main.xml file.

Now let’s launch the application. To do this, select your module from the list of available ones and click the right triangle slightly to the right.

The studio will ask you whether to run the emulator

Select the emulator and press OK. You may have a different emulator name

We wait for the emulator to start and then admire the result

All your new texts should appear on the screen

The application shows us MainActivity, and in turn it reads the file activity_main.xml and displays all the View that we created and configured in it.

In the next lesson we:

Consider a layout file from another angle – XML
let’s see where Activity knows which layout file to read and try setting it to read another file
find out what layout file is used when changing screen orientation (horizontal / vertical)




Discuss in the forum [160 replies]

Lesson 3. Creating an AVD. The first application. The structure of the Android project.


In order to test the applications, we will need an Android Virtual Device (AVD). This is an Android smartphone emulator that we can install and launch applications we create. Let’s create it.

Lesson updated 04/06/2017

In the last lesson, we installed the development environment and the Android SDK.

Now we can finally create our first application and see how it works.

To create an application, we need to create a project in Android Studio. When creating a project, it creates a module. In this module, we draw application screens and write code. And when we launch this module, we get a ready-made application. Therefore, the module is essentially an add-on. And the project is a container for the module.

That is, in the simplest case, the structure of the project is as follows:

There is a project and it has a module. When a project is started, a module is started and we get an Android application created in this module.

In this case: one project = one Android application (one module).

But there can be several modules in one project. And there are several projects you can create.

Here in the first project two modules are created, and in the second project – three modules.

When starting any project, you will need to specify which module you want to run. And each module is a separate Android application.

That is, in this case: one project = multiple Android applications (multiple modules).

We will not go into detail yet which of the proposed schemes is better and more convenient. You can create one project for each lesson and create modules for each lesson. Or you can create a separate project, for example, every 10 lessons. Generally, you can create a separate project for each lesson.

I think we will start with an option: one project for all lessons. And over time, as you get used to it, decide for yourself which option is most convenient for you.

Let’s create a project. We open Android Studio. The startup shortcut must be in the start menu. Or you can open the folder where Android Studio was installed last lesson. The bin folder must have an EXE file.

The development environment has opened. press Start a new Android Studio project.

A project creation window appears. Let’s fill in.

Application name – the name of the project. It will appear in the project list when you open Android Studio. Let’s write here Android lessons (ie Android lessons).

Company Domain – the name of the site, we write startandroid.ru.

Package name is a Java concept, you can see in detail here. In short, it is a prefix for the name of our application classes. As you can see, the package is automatically made on behalf of the site and the name of the project. You can always edit it manually by clicking the edit link on the right.

Project location – the folder on the computer where all the project files will be located. In the last lesson, we created the android folder where we installed Android Studio and SDK. Create an AndroidStudioProjects folder there as well – this folder will store all Android Studio projects. And in it create the Androidlessons folder for our current project.

Most likely now nothing is clear. That’s okay, don’t worry. In each lesson, I will be prompted to fill in these fields, and eventually understanding will come.

press Next

Wizard asks what platform we will code for and the Minimum SDK (the minimum version of Android on which the application can be launched). We leave everything as is.

press Next

Wizard can load the components he needs.

press Next

then select Empty Activity.

press Next

We do not change anything here. For now, we don’t need to know why we need it all.

press Finish.

the project is created

Then the studio opens. When opened, it can show tips.

If you don’t need them, turn off the checkbox.

press Close.

studio opened

But below you can see the progress bar. This means that there is still some action to be done and we have to wait.

And as a result, the project opens

We are immediately open to editing some files. We will not change anything in them, while it is not necessary.

On the left we see the word app is a module. By default, an app module is created when creating a project. We are not interested in it because we will create our modules. But let it remain, I do not advise you to delete it. The wizard that we just went through when creating the project mainly touched on this module.

So the project was created. Now let’s create our own module in the project. I will repeat that for almost every lesson we will create a module in this project. Now let’s create a module (app) for this current lesson. This procedure will be somewhat similar to the creation of the project, but with small differences.

To create a module – select from the menu File -> New -> New modules

The type of module we choose Phone and Tablet Application

press Next

fill in the fields

Application / Library name – directly the name of the application that will appear in the list of applications in the smartphone. We write here FirstProject.

Module name is the name of the module. That is, this name will appear on the left in the list of modules, where there is now an app. Let’s come up with a template for the name of the modules.

For example: p<номер урока(000)><номер проекта в уроке(0)>.

There are three numbers for the lesson number, one for the project number. Also, we will add the name of the program – FirstProject. And all this will be written in small letters and without spaces. The following module name will appear: p0031firstproject.

Package name – Edit the package name manually by clicking edit on the right. Let’s leave ru.startandroid there and add the point and the name of the module.

Minimum SDK leave unchanged.

press Next

then select Empty Activity.

press Next

We do not change anything here

press Finish and we are waiting.

After a while, the module will be created and we will see it in the list on the left. This is p0031firstproject – the value we specified in the Module name field.

You can open this module and see its contents.

Let us briefly walk through the elements of interest to us

file AndroidManifest.xml – program manifest or config file

In the folder java and its subfolders will be all of the application code written by us

Teka really used for resource files of different types.

We will continue to use all of this, and it will become clear what and why is needed.

Let’s finally launch our first app! To do this, select the appropriate module in the drop-down list above

And click (just to the right of the list) the green triangle button (or Shift + F10 combination).

To launch the application, you need some thread real Android device or emulator.

We still have nothing to launch the application for. You can plug in a real device with the cord, and it will appear here (unless there is a problem with the drivers or device settings).

Or you can create an emulator. Click Create New Virtual Device

Here you can select the form factor of the device. Leave what is selected by default.

press Next

Then go to the x86 Images tab and there should be an image that does not have the word Download. That is, completed downloads and we can use it.

In this case, Android 7.1.1 will be installed on the emulator. If you need a different version, download it and use it.

press Next

Then we are asked to specify the name of the emulator and change its settings. We leave everything as is

press Finish

As a result, the device emulator just created appears in the device list and we can use it to run the application.

press Okay

After a while (up to a few minutes) an emulator will appear

And it will start running Android

And as a result, our application will launch

The title in the header is FirstProject. This is what we specified when creating the program.

That is, you have created and launched your first application, with which I welcome you) There are hundreds of such applications and launches ahead.

If the emulator did not show your application, then make sure that Android Studio “sees” this emulator. To do this, click the Android Monitor tab at the bottom left

And in the list of devices just above should be visible emulator Nexus_5X_API_25

If the emulator is listed and the application does not appear, try running the application again by clicking the green triangle (Shift + F10).

If the emulator is not listed, close the emulator and try running the application again.

This lesson was updated in June 2017. Many of the following lessons were written in 2011-2012. Therefore, screenshots may differ from yours. This is normal.

Also, I have to warn that I did and tested the first lessons on Android version 2.3.3. This is stated at the beginning of the lessons. But this does not mean that the lessons are already hopelessly outdated and there is no point in reading them. The code under 2.3.3 and 7.1.1 is in the vast majority of cases exactly the same. New versions of Android add new components, and the past ones usually remain unchanged and are rarely modified or declared obsolete.

P.S.

If you have a project open and you want to see the Android Studio launch window again, select from the menu File > Close Project.

You will see a start window, to the left is a list of your projects.

P.S.S.

If you have a username in Russian, there may be problems. How to solve them can be read on the forum in the branch of this lesson.

If the line above didn’t help, then try this solution again.

In the next lesson, we will be adding different elements to our application and changing their properties.




Discuss in the forum [512 replies]

Lesson 2. Installing Android Studio

Lesson 2. Installing Android Studio


Writing programs requires a development environment. In this tutorial, we'll take a closer look at how to install and configure this development environment.

I will describe the installation can be applied to Windows 7.

Lesson updated 04/06/2017

There are many screenshots and instructions in this article. Keep in mind that software versions are constantly changing and you may look different and your versions may be different.

1. Java SDK (JDK)

Because application development is done in Java, we need to download and install the appropriate SDK, also called JDK (unless, of course, it is already installed).

You can download it here. Click the nearest button there JDK Download, Choose the version for your operating system, download and install. If the link doesn't work then just googly "java sdk download".

After installation, I recommend restarting the computer.

2. Development environment + Android SDK

In the development environment, we will create the application and receive the ready-made application on the output. There are several development environments now, we will choose Google Studio recommended by Google.

Open this page and click Download Android Studio button there. If you need a specific version, click Download Options and choose your version there.

Please note that the file can weigh up to 2 gigs.

So, downloaded the exe file. We launch it. Click Next until he asks for a path.

We are required to indicate two ways. The first path will be used to install Android Studio. The second is to install the Android SDK.

Let's replace them with ours. To do this, let's create a directory android. Just in case, make sure that the path to it is free of spaces and Russian characters. example – <имя диска>: Android. I'll have it d: android. And this way we substitute in the Wizard.

Click Next several times until the installation starts. Android Studio will start when installation is complete. If it does not start, look for its shortcut in Start.

First, it asks if you want to import the previous version's settings.

We leave the bottom point selected and click OK. We don't have any old settings yet.

Next, the installation wizard will appear

click Next

Here we leave the Standard

click Next

Wizard tells us that he needs to download several components to complete the installation

click Next

The download process has gone

Then the unpacking process

Finally, when it's finished, we click Finish, and the Welcome screen opens.

Following these steps, we were provided with a development environment for encoding Android applications. If something does not work out or gives an error – try looking at the forum or googling, you are probably not the first to encounter such a problem and there is already a description of the solution on the network.

Android Studio will periodically plead with you to download and install updates. I strongly advise against doing this until you are new. After the upgrade, you are unlikely to notice any innovations in the new version of the studio, and you can create considerable problems for yourself.

In the next lesson, we'll set up our Android Virtual Device (AVD), create our first app and launch it. AVD is an Android smartphone emulator that lets you run and test applications. Do not connect your smartphone every time.

We will also look at the structure of the draft program.



Discuss in forum (245 replies)

Lesson 1. Introduction.


Good afternoon

This is an introductory lesson. Here we will not codify anything yet, I will note the reasons that led me to create this site.

I started learning about Android development with examples on the official website. I didn't understand half of what I was doing. But some knowledge came out of there and some theories read about the same resource. In this sense, my acquaintance with Android ended) I didn't know where to go next. For some reason I didn't think about books, but in vain …

Later, I came across an article called "Five of the best Android development books". Interest arose, it became clear where to move, I started reading these books. I didn't understand everything, but much more than the first examples. But if you read such books completely from scratch, then many will not be obvious and incomprehensible.

Therefore, I want to try to create tutorials on Android for beginners so that the reader does not have obscure topics behind it. I will try to explain everything in more detail and I will make various examples for greater clarity. With each new lesson, I will introduce and use new concepts and objects and use objects from previous lessons to reinforce.

I try to make each lesson as independent and separate as possible, so that you can get in, look at the right subject and not look at a bunch of unnecessary things. I try to select examples that most clearly reflect the subject of the lesson.

Unlike some authors, I will not teach you programming in "24 hours" or "30 lessons". We all understand that this is impossible) I do not know how many lessons I will receive. I think about one hundred is enough to provide the entire basis in sufficient detail. And then hundreds more will go to various advanced chips. In general, those who start studying, most likely do not have to run much on other sites (except for official help) for additional knowledge. Here you will find a lot of useful, consistent and simple language information.

You have to understand that my lessons are not always an "exactly how to" guide. I can neglect something and I am missing something to show the subject of the lesson and do not give additional material. Therefore, please do not consider everything that is said in the lessons as the only correct way of implementation.

If you have any problems with Android, the site has a great forum, which is always happy to help beginners figure out even the simplest questions. It is true, it is protected from spam by a security question and you can answer to register only by reading the first five lessons. This is a forced defense. But since the introduction of this question, no spammer has entered the forum!

Currently, the lessons cover topics:

– screen creation (in editor and programmatic)
– Click on manipulators
– logs and pop-up messages
– regular menu, context menu
– animation of View components
– creating and calling the Activity (+ return the result)
– the activity cycle of the activity (activity status)
– Intent filter, intent
– data storage (Preferences, SQLite)
– list and adapters
– dialogues
– Package, Parcelable
– Preferences when storing application settings
– works with files
– row file
– XML ​​parsing
– asynchrony (Handler, AsyncTask)
– services
– Content provider
– tactile processing, multi-touch
– fragment
– Action Bar, ActionMode
– widgets
– application keys and signature
– ViewPager
– sound and video playback
– sound recording
– work with the camera
– sensors
– GPS
– Google Maps
– drawing

Keep reading books and lessons will come as I grow. Finally, I think we will reach the point that we will become quite advanced developers in demand on the market. In general, as one zomboyaschik clown says – "do not switch") It will be interesting!

In the next lesson, we will install and configure the Android application development environment.

P.S.

Development is in Java. You may also need knowledge of SQL, XML and other related technologies. You think you know them. If not, then something basic in Java will need to be read.

Google periodically releases Android updates for the development environment. Therefore, the content of the lesson may be slightly outdated and the actual image may differ from the screenshots. If this difference is cardinal or the examples do not work, write it on the forum in the lesson thread. We will update. If the difference is only in the background color of the application or the font size, then this, of course, is not critical and does not affect the lesson message.

It is also noted that the behavior of the code on different versions of the system may be different. We have not checked the performance of the lesson materials on all possible versions, so your results may differ from mine.

P.P.S

It is sometimes said that most of the lessons are made for Android 2.3, and now Android versions have already been released, for example, 100500 and the lessons are outdated. In a way, Weirdo even wrote that 90% of lessons consist of outdated methods. I really don't like to comment stupidly, but for starters I will express my opinion about this whole amateurism.

I cannot restore all the lessons with each version of the new version of Android. Moreover, nothing needs to be redone. The vast majority of lessons will remain the same and everything will work well in any version. In addition, the share of devices on Android 2.X is still high enough to be neglected. And in your applications you will specify the minimum version 2.2 or 2.3, in order not to lose a whole segment of users. So I do not understand the meaning of kipish.

Yes, there are so that, with the release of the new versions, some lessons are really outdated and need to be updated. This, for example, touched on Lesson 52 and we updated it in a separate lesson. But the constant monitoring and updating of the whole lesson due to the fact that there is now a method (horror-horror !!!) outdated is difficult. Remember that I take care of the site in my spare time. And I would rather spend it to write new material than to track and repair outdated methods.

Google help for legacy methods usually provides a link to a new method. So if you see that Eclipse swears by an outdated method, then look for her help and see what has been replaced.

P.P.P.S

According to Android Studio, the situation is about the same. I see no reason to go to AS, because the main thing in the lessons is the code, not the development environment. If not, I will copy the first lessons for AS



Discuss in forum (49 replies)