1th Android app Android simple single-page navigation _android

Source: Internet
Author: User
Tags delete key static class

This example shows how to add a simple single-page navigation, and then shows how to display all the phone numbers dialed on page 1th in page 2nd.

(1) Understand the basic architecture of the Android app through this example.

(2) This example to understand the implementation of Android multi-screen navigation basic technology.

This example is just to give us a more comprehensive understanding of Android app Development, where readers don't have to start with the details of the code, and the related concepts are described separately later.

Run screenshots

Run screenshots (Api19, API21, Api23 implementation code are the same):

Interface operation

Click Convert text to numbers to see the results.

Click the Convert button, and if the conversion succeeds, the Dial button is available, click the Dial button, and observe the pop-up dialog box.

If you click the Dial button, it will automatically dial.

The main design steps are described below.

1. New Project

Select Template: Blank App (Android), project name: Phonewordapp.

After the project is successfully created, delete the Gettingstarted.xamarin (ad file).

2. Interface design

(1) Double hit Open main.axml, respectively, observe the design interface of "Designing" and Source "source" content.

(2) Press the DELETE key to delete the "Hello world,click Me" button.

(3) Drag a "Text (Large)" From the toolbox to the design interface and modify the following properties:

Id:@+id/phonetext

Text: Telephone

Note: The system will automatically add the corresponding code (the same below) to "source" at this time.

(4) Drag a "Plain Text" from the toolbox to the design interface and place it under "Text (Large)" To modify the following properties:

Id:@+id/phonenumbertext

text:138 4912 2599

(5) Drag a button from the toolbox to the design interface and place it under "Plain Text" to modify the following properties:

Id:@+id/buttontranslate

Text: Converting

(6) Drag a button from the toolbox to the design interface below the previous button to modify the property:

Id:@+id/buttoncall

Text: dialing

After the above steps, you get the design interface shown in the following illustration:

(7) Save the file and click the Refresh button at the top of Solution Explorer.

Note: This step is designed to allow the system to find resources within the design interface and automatically generate a corresponding ID so that you can see the smart hints associated with the design interface resource when you type C # code later.

3. Write C # code

(1) Mouse Right click item name à add class, in the pop-up window, select the "Class" template, Name: PhoneTranslator.cs, as shown in the following figure, click the "Add" button.

The

Then changes the PhoneTranslator.cs to the following code:

Using System.Text; 
      namespace Phonewordapp {public static class Phonewordtranslator {public static string Tonumber (String raw) { if (string.
      Isnullorwhitespace (Raw)) {return ""; else {raw = raw.
      Toupperinvariant ();
      var newnumber = new StringBuilder (); foreach (var c in raw) {if ("-0123456789").
        Contains (c)) Newnumber.append (c);
          else {var result = Translatetonumber (c);
        if (result!= null) newnumber.append (result);
    } return newnumber.tostring ();
    static bool Contains (This string keystring, char c) {return Keystring.indexof (c) >= 0; } static int? Translatetonumber (char c) {if ("ABC").
      Contains (c)) return 2; else if ("DEF".
      Contains (c)) return 3; else if ("GHI".
      Contains (c)) return 4; else if ("JKL".
     Contains (c)) return 5; else if ("MNO".
      Contains (c)) return 6; else if ("PQRS".
      Contains (c)) return 7; else if ("TUV".)
      Contains (c)) return 8; else if ("WXYZ".
      Contains (c)) return 9;
    return null;
 }
  }
}

(2) to open MainActivity.cs, change the file to the following code:

Using System;
Using Android.app;
Using Android.content;
Using Android.runtime;
Using Android.views;
Using Android.widget;
Using Android.os;
Using System.Collections.Generic;  namespace Phonewordapp {[Activity (Label = ' Phonewordapp ', Mainlauncher = true, Icon = ' @drawable/icon ')]] public class

    mainactivity:activity {static readonly list<string> phonenumbers = new list<string> (); protected override void OnCreate (Bundle Bundle) {base.
      OnCreate (bundle);

      Setcontentview (Resource.Layout.Main);
      var phonenumbertext = findviewbyid<edittext> (Resource.Id.PhoneNumberText);
      var buttontranslate = findviewbyid<button> (Resource.Id.buttonTranslate);
      var buttoncall = findviewbyid<button> (Resource.Id.buttonCall); buttoncall.enabled = false; Disables the dial button string translatednumber = String.
      Empty; Buttontranslate.click + = (s, e) => {translatednumber = Phonewordtranslator.tonumber (PhonenumbertexT.text); if (string.
          Isnullorwhitespace (Translatednumber)) {buttoncall.text = "dial";
        buttoncall.enabled = false; else {buttoncall.text = ' broadcast number: ' + Translatednumber + ', click OK!
          ";
        Buttoncall.enabled = true;

      }
      };
      var buttoncallhistory = findviewbyid<button> (Resource.Id.buttonCallHistory);
        Buttoncallhistory.click + = (sender, E) => {var intent = new Intent (this, typeof (Callhistoryactivity)); Intent.
        Putstringarraylistextra ("Phone_numbers", phonenumbers);
      StartActivity (Intent);

      };
        Buttoncall.click + = (s, e) => {phonenumbers.add (translatednumber);
        Buttoncallhistory.enabled = true;
        When you click Dial, try dialing var calldialog = new Alertdialog.builder (this); Calldialog.setmessage ("Tel:" + translatednumber + ", dial?)
        "); Calldialog.setneutralbutton ("dialing", delegate {var callintent)= new Intent (Intent.actioncall);
          Callintent.setdata (Android.Net.Uri.Parse ("Tel:" + translatednumber));
        StartActivity (callintent);
        });
        Calldialog.setnegativebutton ("Cancel", delegate {});
      Calldialog.show ();

    };
 }
  }
}

(3) Rebuild the project to ensure no errors.

Note: The icon.png in the Drawable folder is the icon to display, or you can swap it for a different icon file.

(4) Select the properties of the item under the main menu, and in the pop-up window, check the "Call PHONE" permission:

Note:

(1) This step must be done, or because the app does not have dial-up permission, dial-up function will fail.

(2) After setting, view the code that is automatically added in the Androidmanifest.xml file under the Properties folder, and understand the role of the permissions setting.

4, debugging operation and code fragment explanation

Select an emulator, and then press <F5> to debug and run.

Note: If you use an emulator that is less than API 23, you must set the project properties (the main Menu à item property) and use the corresponding version of the API to compile the application, otherwise the application may flash out or show "application stopped" when running on the emulator.

The following explains the meaning of the previously implemented code fragment:

(1) How to display the Alert dialog box

The detailed usage of Alertdialog is shown in the 6th Chapter UI Design (iii)--dialog box.

(2) How to dial

The following code shows how to invoke the system function implementation dial:

var callintent = new Intent (Intent.actioncall);

Callintent.setdata (Android.Net.Uri.Parse ("Tel:" + translatednumber));

StartActivity (callintent);

Note: Before running, you need to check "call PHONE" settings to allow dialing permission, otherwise the run will be abnormal:

5, create a 2nd screen tracking history

(1) Open the Strings.xml file under the Values folder and add the following code:

<?xml version= "1.0" encoding= "Utf-8"?>

<resources> ...

<string name= "Callhistory" > Dialing records </string>

</resources>

(2) Click the Refresh button at the top of Solution Explorer, or rebuild the project.

Note: Select one of these to make the C # code recognize it.

(3) Open Main.axml, drag a button from the toolbox to the Main.axml design interface, place it below the previous button, and modify the properties:

Id:@+id/buttoncallhistory

Text: @string/callhistory

Enabled:false

Note: The meaning of the @string/callhistory is to provide the value of the variable in the Strings.xml file under the Values folder.

At this point, you can see that "string/callhistory" automatically becomes the dial record.

Description: The practice of setting variable values in this step is the recommended practice in the actual Android app project, and the advantage of this is that it improves the efficiency of Android app operation. While step 1 is a hard-coded approach, hard coding is not a recommended practice in Android apps, and step 1 is just easier to understand when you get started.

(4) Right click on the project name, select "Add ..." to "New item", in the pop-up window, select the "Activity" template, FileName: CallHistoryActivity.cs, click "Add". Then change the file to the following (omit the using ...). ):

Namespace Phonewordapp

{

[activity (Label = ' callhistoryactivity ')] public

class Callhistoryactivity: Listactivity

{

protected override void OnCreate (Bundle Bundle)

{

base. OnCreate (bundle);

var phonenumbers =

Intent.Extras.GetStringArrayList ("Phone_numbers")?? new String[0];

This. ListAdapter = new Arrayadapter<string> (this,

Android.Resource.Layout.SimpleListItem1, phonenumbers);

}

}

}

of which, C = a?? b The meaning of the equivalent: if (a!= null) {c = A;} else {c = b;}

(5) Modify the MainActivity.cs file, the goal is to collect the 1th screen interface at the time of the runtime dial all the phone number, and it is displayed on the 2nd screen. Add the following code to the MainActivity.cs file:

... using System.Collections.Generic; namespace E01phonewordapp {[Activity (Label = "E01phonewordapp", Mainlauncher = true, Icon = "@drawable/icon")]

Class Mainactivity:activity {static readonly list<string> phonenumbers = new list<string> (); protected override void OnCreate (Bundle Bundle) {... var buttoncallhistory = findviewbyid<button> (resource.id.b

Uttoncallhistory);

Buttoncallhistory.click + = (sender, E) => {var intent = new Intent (this, typeof (Callhistoryactivity)); Intent.

Putstringarraylistextra ("Phone_numbers", phonenumbers);

StartActivity (Intent);


};

Buttoncall.click + = (s, e) => {phonenumbers.add (translatednumber);

Buttoncallhistory.enabled = true;

When you click Dial, try dialing var calldialog = new Alertdialog.builder (this); Calldialog.setmessage ("Broadcast number:" + Translatednumber + ", dial?)

"); Calldialog.setneutralbutton ("dialing", delegate {//Create intent to dial phone, var callintent = new Intent (Intent.actionca

ll); Callintent.setData (Android.Net.Uri.Parse ("Tel:" + translatednumber));

StartActivity (callintent);

});

Calldialog.setnegativebutton ("Cancel", delegate {});

Calldialog.show ();

};

 }

}

}

(6) Rebuild the project to ensure no errors.

(7) Run, and then dial a number (for example, 12345678901), and then view the dialing records. The following figure is a running effect viewed with a different emulator (you can create a variety of different emulators to see the same project in effect):

Here, we have finished the 1th android application written in C #.

The above is the entire content of this article, I hope to help you learn, but also hope that we support the cloud habitat community.

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.