Xamarin咱們在上節已經教你們如何去部署它的環境了,今天來講一個實際的例子,使用android客戶調用.net web api的一個接口,併發送POST請求,當服務端回到請求後作出響應,客戶端android將響應的內容輸出,並跳換到別一個Activity頁面,在新視圖上加載網頁內容到webView控件上,整個流程結束!html
一 在主頁面上添加幾個表單元素,帳號,密碼,登錄按鈕,並在Activity類的OnCreate方法中爲它們賦值,並添加按鈕的click事件android
protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); // Set our view from the "main" layout resource SetContentView (Resource.Layout.Main); // Get our button from the layout resource, // and attach an event to it Button button = FindViewById<Button> (Resource.Id.myButton); button.Click += delegate { button.Text = string.Format ("{0} clicks!", count++); }; Android.Util.Log.Info ("normal", "日誌zzl"); var loginBtn = FindViewById<Button> (Resource.Id.loginBtn); var username = FindViewById<TextView> (Resource.Id.username); var password = FindViewById<TextView> (Resource.Id.password); var result = FindViewById<TextView> (Resource.Id.result); loginBtn.Click += delegate { string url = "http://api.xuexiba.com/v1/User/Login"; //建立HttpClient(注意傳入HttpClientHandler) using (var http = new HttpClient ()) { var content = new FormUrlEncodedContent (new Dictionary<string, string> () { { "username",username.Text }, { "password",password.Text } }); var response = http.PostAsync (url, content); result.Text = response.Result.Content.ReadAsStringAsync ().Result; Intent intent = new Intent(this, typeof(ViewPageActivity)); StartActivity(intent); } }; }
二 在ViewPageActivity裏添加一個webView用來顯示網頁的內容,以下代碼web
protected override void OnCreate (Bundle savedInstanceState) { base.OnCreate (savedInstanceState); SetContentView (Resource.Layout.ViewPage); var webView = FindViewById<WebView> (Resource.Id.webView); //啓用Javascript Enable webView.Settings.JavaScriptEnabled = true; //載入網址 webView.LoadUrl ("http://www.sina.com"); //直接在當前webView上打開 webView.SetWebViewClient (new CustWebViewClient ()); }
注意,代碼webView.SetWebViewClient (new CustWebViewClient ())表示使用現有的webView加載網頁內容,而若是不加這行,那麼網頁將使用系統自帶的瀏覽器進行加載,api
下載看一下CustWebViewClient 這個類的內容瀏覽器
public class CustWebViewClient : WebViewClient { public override bool ShouldOverrideUrlLoading (WebView view, string url) { view.LoadUrl (url); return true; } }
OK,在咱們設計頁面時,能夠直接從工具箱上進行拖動,最後佈局向這樣併發
最後進行APK的生成,咱們的程序包就算完成了!ide