Program on Android is not so complicated (part 2)

in a post above saw the panorama of the necessary environment to program an application that runs on any Android device has changed substantially reduced simply to a free powerful tool, that also provides Google: Android Studio.

in this post will continue deepening in the development of applications with Android Studio stopping in one of the more flashy in any application: the GUI

Android provides a vocabulary of XML that corresponds to the subclasses of View and ViewGroup , so that you can define your UI in XML using a hierarchy of UI elements and designs are subclasses of ViewGroup

usually , the View objects are widgets in the UI as buttons or text fields and ViewGroup objects are containers of invisible views that define the disposition of the secondary views, as in a grid or in a vertical list.

design interface

Although there are endless possibilities of interface design, to begin with, we will use a simple linear design that places all the graphic elements one after the other:

  • Project window Android Studio, open the file activity_main.xm l ( app > beef > layout > activity_main.xml) . This XML file defines the design of your activity and contains the default “Hello World” text view.
  • when opening a design file, first thing he sees is the editor of design, but many programmers prefer to work directly with the XML; Therefore, click on the tab Text at the bottom of the window to move to the text editor.
  • delete the entire contents of the file and insert the following XML:
      <?   xml version   =   "1.0"   encoding   =   "utf-8"  ? >   < LinearLayout     xmlns:android     "http://schemas.android.com/apk/res/android" =     xmlns:tools     "http://schemas.android.com/tools" =     android:layout_width     "match_parent" =     android : layout_height     "match_parent" =     android:orientation   = 'horizontal'     >     

LinearLayout is a group of views (a subclass of ViewGroup ) which has the secondary views in vertical or horizontal direction as specified by the attribute android:orientation . Each child element of a LinearLayout appears on the screen in the order in which it appears in XML.

are needed other two attributes, android:layout_width and android:layout_height , to specify the size of all views.

because LinearLayout to is the root in the design view, should deal with the area of the full screen that is available to the app when you set the width and height in "match_parent" . This value States that the view should expand its width or height to match the width or height of the primary view.

Add a text

field in the file activity_main.xml , within the element , add the following element :

  < LinearLayout     xmlns:android     "http://schemas.android.com/apk/res/android" =     xmlns:tools     "http://schemas.android.com/tools" =     android : layout_width   =   "match_parent"     android:layout_height   =   "match_parent"     android:orientation   = 'horizontal'     >    < EditText  android:id="@+id/edit_message"   android:layout_weight   =     "1" android : layout_width   =   "0dp"    android:layout_height   =   "wrap_content"  android:hint="@string/edit_message"  / >        

A below, provides a description of the attributes of the which has added:

  • android : id: that provides a unique identifier for the view, which can be used to refer to the object from code of the app, read and manipulate the object. The at sign (@) is required when reference is made to any object of XML resources and is followed by the type of resource ( id in this case), a slash and the name of the resource (). It equals ( + ) before the resource type is needed only when you are defining a resource ID for the first time. When you compile the app, the name is used by the SDK tools of the ID to create a new resource ID in the file R.java of your project that references the element EditText . With the ID resource declared once in this way, other references to the identifier does not need the plus sign. Required the use of more single sign when you specify a new ID resource and is not needed for concrete, such as strings or design resources. Check the side box for more information about the resource objects.
  • android:layout_width and android:layout_height : rather than using specific sizes for the width and height, the value "wrap_content" Specifies that the view must only be large enough to fit the contents of the view. If you instead use "match_parent" , EditText element will occupy the display because the size of the parent element will match LinearLayout . For more information, query the Guide Disenos.fijar the width at zero (0 dp) does the entry box to occupy the screen width and improves the performance of the design, since the use of "wrap_content" as the width requires the system to calculate a wide, which eventually is irrelevant because the weight value requires another calculation of width to fill the remaining space.
  • android:hint : this is a default string to display when the text field is empty. Instead of using a string encoded as a value, the value "@string/edit_message" refers to a resource string defined in a separate file. Since this refers to a particular resource (not simply an identifier), you don’t need the plus sign. Without however, because the string resource, have not been identified will appear a compiler error. This string resource has the same name as the ID of the element: edit_message . However, the references to resources always have areas by type of resource (such as id or string ); Therefore, use the same name does not generate conflicts.

Add resources

by default, in a project of Android includes a resource file in a string in a file named strings.xml ( res > values > strings.xml) .

stop, add new strings to the file strings.xml follow these steps.

  1. Project window , res open > values > strings.xml .
  2. add two strings so that the file is visible in this way:
      <?   xml version   =   "1.0"   encoding   =   "utf-8"  ? >        < string   name     "app_name"   = >   My First App         < string  name      'edit_message'   = > insert a message        < string   name     "button_send"   = > Send         

for the text in the user interface, always specify each string as a resource. Strings of text resources allow you to manage all the texts of UI in a single location, which makes it much easier to find and update the text.

externalize the strings also allows you to locate your application ara different languages to provide alternative definitions for each string resource.

Add a button

replace file activity_main.xml and add a button after the widget .

file should look like the following:

     < Button     android:layout_width     "wrap_content" =     android:layout_height   =   "wrap_content"   android:text="@string/button_send"  / >   

as we see and ste button does not need the attribute android : id because not be reference to it from the code of the activity.

currently, the configuration of the design makes widgets EditText and Button have the necessary size to fit its content, as shown below

this works well for the button, but not so well for the text field because the user could write something longer. It would be good to fill the width of the excess screen with the text field. You can do it inside a LinearLayout with the property of weight , which you can specify by using the attribute android:layout_weight .

the weight value is a number that specifies the amount of the remaining space that each view should consume, relative to the amount consumed by views of the same level. This works as the amount of ingredients in a recipe for a drink: “2 parts of soda, 1 part syrup” means that two-thirds of the drink are refresh. For example, if you give to a view a value weight of 2 and another a value weight of 1, the sum is 3, so the first full view 2/3 of the remaining space and the second sight complete the rest. If you add a third view and give it a value weight of 1, the first view (with a weight of 2) now gets 1/2 of the remaining space, while the other two are 1/4.

all views default weight value is 0, so if you specify any value of weight greater than 0 for a view only, view such complete the remaining space once the required space is assigned to all views.

the result of modify the file activity_main.xml , should offer the following aspect:

  

the following is look like should have layout file activity_main.xml full:

  <?   xml version   =   "1.0"   encoding   =   "utf-8"  ? >   < LinearLayout   xmlns:android     "http://schemas.android.com/apk/res/android" =     xmlns:tools     "http://schemas.android.com/tools" =     android:orientation   = 'horizontal'       android : layout_width     "match_parent" =     android:layout_height     "match_parent"   = >     < EditText  android:id="@+id/edit_message"   android:layout_weight   =   "1"     android:layout_width     "0dp" =     android : layout_height   =   "wrap_content"   android:hint="@string/edit_message"  / >     < Button     android:layout_width     "wrap_content" =     android:layout_height   =   "wrap_content"   android:text="@string/button_send"  / >     

give functionality to the button

once we have defined button have to assign functionality, for which we can follow the following steps:

  1. res file > layout > activity_main.xml , add the attribute android:onClick element
  2. java file > com.example.myfirstapp > MainActivity.java , add the stub method sendMessage () as shown below:
      public class     MainActivity     AppCompatActivity extends   {  @Override   protected   void onCreate    (Bundle savedInstanceState)   {    super  . []}} onCreate [19459023  (savedInstanceState);  setContentView   (R.[)  layout  .   activity_main  );  {{  }      / * Called when the user clicks the Send button * /     public void      sendMessage (View view)   {    / / Do something in response to button    }   }  

    so the system match this method with the name of the method provided to android:onClick the signature must be exactly as shown. Specifically, the method must be:

    • be public
    • have a return value empty
    • have a View object as the only parameter (this will be the View to which it was clicked)

then complete this method to read the contents of the text field and submit the text to another activity.

create an intent

a I ntent is an object that provides link between separate components runtime (as two activities) representing the “intention of making something” PPPs.

in the file MainActivity.java , add the code () below to sendMessage:

  public     MainActivity class extends     AppCompatActivity   {     public   end   static String    [19459023}] EXTRA_MESSAGE   =   "com.example.myfirstapp.MESSAGE"  ;    @Override   protected   void onCreate    (Bundle savedInstanceState)   {    super  . []} onCreate [19459023  (savedInstanceState);  setContentView   (R.[)  layout  .   activity_main  );  {  }     / * Called when the user clicks the Send button * /     public void      sendMessage (View view)   {     Intent  intent    =   new Intent    (this)} , DisplayMessageActivity    .   class  );  EditText      editText   =  (EditText) findViewById    (R.[)  id  .   edit_message  );  String      message   =   editText  .    () getText.     () toString;   intent  .  putExtra   (EXTRA_MESSAGE, message);  startActivity   (intent);   {{  }  }  

Android Studio will display errors Cannot resolve symbol because this code refers to classes that are not imported. You can solve some of these errors with the functionality of "importation of class" Android Studio by pressing Alt + Enter (or option + return in Mac).

their imported must be terminated in the following way: import

 

android . content . Intent ; import android . support . v7 . app . AppCompatActivity ; import android . I . Bundle ; import android . view . View ; import android . widget . EditText ;

sendMessage () take place many, many processes. For this reason, we will explain what happens.

Intent Builder takes two parameters:

putExtra method () adds the value of the EditText to the intent. An Intent can carry data as key-value pairs called extra types . The key is a EXTRA_MESSAGE constant public because the next activity uses the key to return the text value. It is good to define keys for intents extra fields using the name of the package of your app as prefix. This ensures that the keys are unique, where your app to interact with other apps.

startActivity method () starts an instance of the DisplayMessageActivity specified by the Intent . You must now create the class.

create the second activity

  1. in Project window , click with the right mouse button on the folder app and select New > Activity > Empty Activity .
  2. Configure Activity window , enter "DisplayMessageActivity" in Activity Name and click on Finish

Android Studio automatically performs three actions:

  • creates DisplayMessageActivity.java class with an implementation of the method onCreate () mandatory.
  • creates the layout file activity_display_message.xml corresponding.
  • adds the item mandatory in AndroidManifest.xml .

If you run the app and you click on the Send button in the first activity, the second activity will start, but will be empty. This happens because the second activity uses the empty default layout provided by the template.

show

A message then can modify the second activity so that it shows the message that passed the first.

  1. in DisplayMessageActivity.java , add the following code to the method onCreate () :
    @Override  protected   void onCreate    (Bundle savedInstanceState)   {    super  . []} onCreate [19459023  (savedInstanceState);  setContentView   (R.[)  layout  .   activity_display_message  );  Intent      intent   =   getIntent  ();  String      message   =   intent  .   getStringExtra  (MainActivity.[)( EXTRA_MESSAGE   );  TextView      textView   =   new TextView    (this);   textView  .  setTextSize   (40);   textView  .  setText   (message);  ViewGroup      layout   =  (ViewGroup) findViewById    (R.[)  id  .   activity_display_message  );   layout  .  addView   (textView); { }  
  2. press Alt + Enter (or option + return in Mac) to import missing classes. The imported must have the following termination: import
       android  .   content  .   Intent  ; import     android  .   support  .   v7  .   app  .   AppCompatActivity  ; import     android  .   I  .   Bundle  ; import     android  .   view  .   ViewGroup  ; import     android  .   widget  .   TextView  ;  

many processes take place. See the explanation:

  1. the called getIntent () captures the intent that started the activity. All Activity is invoked through an Intent , regardless of how the user is navigating to the point in question. The called getStringExtra () displays the data of the first activity.
  2. TextView element is created programmatically, and set the size and message of this.
  3. TextView element is added to the design identified by R.id.activity_display_message . The design is transferred to ViewGroup because it is the superclass of all designs and contains the method addView ().

Note: it is possible that the XML design generated by previous versions of Android Studio does not include the attribute android: id . The call findViewById () will fail if the design does not have the attribute android: id . In this case, open the file activity_display_message.xml and add the atributoandroid:id="@+id/activity_display_message" to the design element.

implementation of the app

to see what will now have their app on your device, click Run in the toolbar.

when it opens, type a message in the text field and click Send . The second activity replaces the first on-screen, whereupon the message to ingresoe in the first activity will be shown.

that's it. You have created a new app for Android!

more information in developer.android.com

Be the first to comment

Leave a Reply