Android (Xamarin) Tour (four)

Source: Internet
Author: User

Original: Android (Xamarin) Tour (four)

So late, probably because of a little thing, said open the blog Park to see, the results http://www.cnblogs.com/mindwind/p/5125248.html This article instantly attracted me. Secretly recall, ten years later, what I look like, or that? For the sake of livelihood, for that little future to fight for ...

In writing this, I suddenly found that I wrote on an article three, unexpectedly was reproduced, haha, welcome technical exchange.

Just go ahead.

Android (Xamarin) Tour (i)This article speaks of the simple configuration of Xamain, the directory manifest file for Android files, and some simple controls. Android (Xamarin) Tour (two) This article introduces some simple controls. There is also a partial list of interfaces.   Android (Xamarin) Tour (three)

  This article says a few simple layout controls, prompt settings, and dialog box settings.

Today we mainly talk about other data components, broadcasts, services.

First, data components

  1. Data adapter

Interface we drag a ListView directly to the left sidebar and then bind the data through the background.

 var list = new list<idictionary<string, object>> ();            Random rand = new Random ();                for (int i = 0; i < 8; i++) {var dic = new javadictionary<string, object> (); Dic.                ADD ("name", "Tel:" + i); Dic. ADD ("Time", "Re" +rand.                Next (100,999)); List.            ADD (DIC);                } simpleadapter Sam_adapter = new Simpleadapter (this, list, Resource.Layout.layout_SimpleAdapter,            New string[] {"Name", "Time"}, new int[] {Resource.Id.tv_name, Resource.Id.tv_time});            var listview = findviewbyid<listview> (Resource.Id.listView1); Listview. Adapter = Sam_adapter; 

Explain the list<idictionary<string here , object>> (), this is to create a new data object, here the javadictionary<string, Object> () is actually the dictionary<t,t> type in C #, and here is the addition of data.

In Android, like this, you need a data adapter, which is the ListView here . Adapter, we can directly find the assignment by findviewbyid<listview>, here, with a relatively complex simpleadapter, Where the third parameter Resource.Layout.layout_SimpleAdapter , this is a layout file of its own definition, of course, you can directly take the system layout file, see the code below.

            var list = new list<string> () {"A.mp3", "B.mp3", "C.mp3"};            arrayadapter<string> a_adaper = new Arrayadapter<string> (This, Android.Resource.Layout.SimpleSpinnerItem, list);

So, you can see the first parameter this, meaning that the activity is currently active, the second parameter refers to the layout of the system .

  2, Spinner

The control provides a quick way to select a value from a collection of data. By default, spinner displays the currently selected value, and clicking Spinner pops up a dropdown menu with all the optional values, from which you can select a new value for spinner. Again, the adapter is used to assign values directly. As follows.

            var list = new list<string> () {"A.mp3", "B.mp3", "C.mp3"};            arrayadapter<string> a_adaper = new Arrayadapter<string> (This, Android.Resource.Layout.SimpleSpinnerItem, list);            Spinner sp = findviewbyid<spinner> (Resource.Id.spinner1);            Sp. Adapter = A_adaper;            Sp. Setpromptid (Resource.String.Title);

The Setpromptid here is a heading through this setting, and here I am a constant defined in my own Strings.xml file.

  3, the GridView

Directly using the data control Simpleadapter mentioned above, drag a GridView over the interface directly.

            var list_dic = new list<idictionary<string, object>> ();            for (int i = 0; i < 8; i++)            {                var dic = new javadictionary<string, object> ();                Dic. ADD ("name", "Tel:" + i);                Dic. ADD ("icon", Resource.Drawable.Icon);                Dic. ADD ("Time", DateTime.Now.Second + ":" + DateTime.Now.Millisecond);                List_dic. ADD (DIC);            }            Simpleadapter sam_adapter = new Simpleadapter (this, List_dic, Resource.Layout.layout_SimpleAdapter,                new string[] {"Name", "icon", "Time"},                new int[] {Resource.Id.tv_name, Resource.Id.tv_time});            var gv1 = findviewbyid<gridview> (Resource.Id.gridView1);            Gv1. Adapter = Sam_adapter;

The data is also bound by the adapter Adapter.

Attached: Some properties of the GridView (in fact Baidu can be found casually)

To set the number of columns using Android:numcolumns
Use Android:columnwidth to set the width of each column
If the value of Android:numcolumns is changed to "Auto_fit", with Android:columnwidth can adapt.
Use android:horizontalspacing to set spacing without columns
Use android:verticalspacing to set spacing per line

Second, communication

Communication here may not be used properly, in fact, this has been mentioned in the previous, Intent

    1. Basic Jump

    Let's start by creating a basic page for receiving.

    On the Layout folder, select Add New item to create a new page of Android layout directly.

The purpose of this page is to confirm success when jumping past.

    Next, we add a new Activity.

For the sake of the neat interface, we add a new item directly to the project.

The goal is to have the mainactivity under the directory and then add the code Setcontentview.

Using system;using system.collections.generic;using system.linq;using system.text;using Android.App;using Android.content;using android.os;using android.runtime;using android.views;using Android.Widget;namespace Test015{    [Activity (Label = "Activity2")] public    class activity1:activity    {        protected override void OnCreate ( Bundle savedinstancestate)        {            base. OnCreate (savedinstancestate);            Bound View            Setcontentview (RESOURCE.LAYOUT.LAYOUT1);}}}    

The purpose of this interface is to allow the interface to be received.

Add the following code to the Mainactivity interface.

            Intent it = new Intent (this, typeof (Activity1));            StartActivity (it);            It. PutExtra ("Test", "Mono for Android");            StartActivity (it);            Finish ();

The startactivity here is to initiate this intent, and the purpose behind the PutExtra is to pass on a single ration labeled name . Then, we continue to add code to this page of Activity1 , the data passed over to receive, print out. Of course, to achieve this, we still have to implement the Idialoginterfaceonclicklistener interface

            Toast.maketext (This, Intent.getstringextra ("test"), Toastlength.long). Show ();
        public void OnClick (Idialoginterface dialog, int. which)        {            Toast.maketext (this, which + "", Toastlength.short) . Show ();        }

In the jump Activity inside directly to receive can, using intent.getstringextra ("test") , through this unique name to get this variable.

You can see the effect in the virtual machine by booting directly.

   2. Implement implicit intent

On the basis of the jump, we add the filter on this activity page of Activity1, the position of this filter, to be added in the public class Activity1:activity , Idialoginterfaceonclicklistener The code in front of the line.

//Create an implicit view//only deal with HTTP-related [Intentfilter (new string[] {Intent.actionview}, Categories = new string[] {Intent.categorydefault}, Datascheme = "http")] 

  public class Activity2:activ Ity,idialoginterfaceonclicklistener
{
public void OnClick (Idialoginterface dialog, int which)
 &nbs p;      {
            Toast.maketext (this, which + "", Toastlength.short). Show ();
       }

        protected override void OnCreate (Bundle savedinstancestate)
        {
             base. OnCreate (savedinstancestate);
            Setcontentview (RESOURCE.LAYOUT.LAYOUT1);
ImageButton ibtn = findviewbyid<imagebutton> (Resource.Id.imageButton1);
Ibtn. Click + = delegate {URL ();};
}
}

Through the comments here we can see what this means, this is to add a Web page to open the implicit intent , such as our mobile phone system installed a lot of browsers, my phone is not a UC browser, every time you start, there is a detection, is not the default browser, this is what we mean. The following is the interface that was mentioned earlier, and the binding page for the settings.

To implement this, we first have to have a method of opening the URL. To add a button to the Layout1.axml interface we added earlier, the purpose of this button is to implement a jump intent, which is to show the effect of our implicit intent here. Add the Click event in the code (not in this section here), and the jump code.

        private void URL ()        {            Intent it = new Intent ();            It. Setaction (Intent.actionview);            It. SetData (Android.Net.Uri.Parse ("http://www.baidu.com"));            StartActivity (it);        }

OK, to start here, when we jump over and then click on this page, we are not able to have a choice.

Third, broadcasting

Broadcast this I do not know how to explain, simply say, that is, if we want to open the software, and then jump directly to the start interface, some applications will tell you, has been transferred to the background to run, this broadcast means that we also have such a unique indicator is monitored, The purpose of broadcasting is to listen for events.

For details, refer to:http://www.cnblogs.com/qianlifeng/archive/2011/03/06/1972305.html

We add a project directly. The interface code is as follows:

<?xml version= "1.0" encoding= "Utf-8"? ><linearlayout xmlns:android= "http://schemas.android.com/apk/res/ Android "android:orientation=" vertical "android:layout_width=" fill_parent "android:layout_height=" Fill_parent "    ; <button android:id= "@+id/mybutton" android:layout_width= "fill_parent" android:layout_height= "Wrap_ Content "android:text=" @string/hello "/> <button android:id=" @+id/register "Android:layout_w Idth= "Fill_parent" android:layout_height= "wrap_content" android:text= "register broadcast"/> <button Andro Id:id= "@+id/cancel" android:layout_width= "fill_parent" android:layout_height= "Wrap_content" android:t ext= "unregister"/> <button android:id= "@+id/send" android:layout_width= "Fill_parent" Android:layo ut_height= "wrap_content" android:text= "Send broadcast"/> <textview android:text= "text" Android:layout _width= "Match_parent" android:layout_height= "Wrap_content" android:textsize= "24sp" android:id= "@+id/textview1"/></LinearLayo Ut>

The

  Background mainactivity code is as follows:

Using system;using android.app;using android.content;using android.runtime;using android.views;using Android.Widget; Using android.os;using java.util;namespace test017{[Activity (Label = "myapk", Mainlauncher = true, Icon = "@drawable/I        Con ")] public class Mainactivity:activity {int count = 1;  Private Receivebroadcast Receivebroadcast; Broadcast instance///<summary>///Dial-up interface///</summary> private String flag = "Android.intent . Action.        Call_button "; protected override void OnCreate (bundle bundle) {base.            OnCreate (bundle);            Set our view from the "main" layout resource Setcontentview (Resource.Layout.Main);            Button button = findviewbyid<button> (Resource.Id.MyButton); button. Click + = delegate {button. Text = string. Format ("{0} clicks!", count++);            };            Register Button btn_register = findviewbyid<button> (Resource.Id.Register); Btn_reGister.            Click + = Btn_register_click;            Cancel Button btn_cancel = findviewbyid<button> (Resource.Id.Cancel); Btn_cancel.            Click + = delegate {Unregistelinster ();};            Send broadcast Button btn_send = findviewbyid<button> (Resource.Id.Send); Btn_send.        Click + = Btn_send_click;  } private void Btn_send_click (object sender, EventArgs e) {Intent Intent = new Intent (); Itent is the content we are sending intent.            PutExtra ("Data", "This was data from broadcast" + DateTime.Now.ToString ("Yyyy-mm-dd HH:ss:mm")); Intent.   Setaction (flag);   Set your action on this broadcast, only the recipient who is the same as this action can receive the broadcast sendbroadcast (intent);        Send broadcast} private void Unregistelinster () {unregisterreceiver (receivebroadcast); }//<summary>//Inherit///</summary> public class Receivebroadcast:broadcastre ceiver {public override void ONreceive (context context, Intent Intent) {/////The purpose here is to monitor if your broadcast is working.                ProgressDialog P_dialog = new ProgressDialog (context); P_dialog.                Setmessage ("Loading ..."); P_dialog.            Show (); }} private void Btn_register_click (object sender, EventArgs e) {receivebroadcast = new R            Eceivebroadcast ();            Intentfilter filter = new Intentfilter (); Filter.    Addaction (flag);        The broadcast Registerreceiver (receivebroadcast, filter) can only be received by the recipient who holds the same action; }    }}

We run directly and register this broadcast first. Then click Send Broadcast, we will be able to see the loading of the prompt message.

    

About Android's four components Activity,service service, content provider contents provider, Broadcastreceiver broadcast receiver. So far, we've talked about Activity and Broadcastreceiver broadcast receivers. Please wait for the next update, because I am also a novice ah.

Say something about the installation of this thing, do not know what win 8 is. I installed Android studio, SDK Manager and AVD Manager without any problems, but Android studio this main interface can not start, finally in the Win7 virtual machine on a half-day, yes, on Win XP interview on a bit, This may not work because of a problem with the JDK file version.

The amount, two o'clock in the morning, a little hungry, hope that the big guys see a bit hungry face on, welcome to testify wrong, move up your cute little hand, silently to recommend, need the source of students can leave a message.

Android (Xamarin) Tour (four)

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.