如何将一段代码绑定到按钮点击事件Xamarin Android

时间:2016-08-07 03:14:20

标签: c# android xamarin.ios

概述:

我需要创建一个应用程序,通过TCP将简单的字符串发送到PC上的服务器。我正在使用Xamarin在Visual Studio 2015中编写此应用程序。今天早些时候我已经让TCP发送功能,但我希望应用程序看起来更好。我下载了一个模板,并开始在代码中添加回来。然而,当我试图运行程序时,我遇到了一个问题。它给了我Object未设置为Instance错误。

基本上,我是一个新手,并且不知道在何处设置按下按钮时将执行的代码。任何帮助都表示赞赏,请记住,我非常沮丧(我道歉),如果对我有同样的帮助,我会表现得很友善:)

谢谢大家,这是代码:

totalTokens = getTokens(username, function(tokens){
    // console.log(tokens); why does this work, but the line below doesn't? 
    return tokens;
});

$('#username_field').text('Tokens: ' + tokens);

现在这里是设计代码:

    using Android.App;
using Android.Content.PM;
using Android.Content.Res;
using Android.OS;
using Android.Support.V4.Widget;
using Android.Views;
using Android.Widget;

using AndroidApp1.Fragments;
using Android.Support.V7.App;
using Android.Support.V4.View;
using Android.Support.Design.Widget;
using System.IO;
using System;
using System.Runtime.InteropServices.ComTypes;
using System.Text;
using System.Net.Sockets;

namespace AndroidApp1.Activities
{
    [Activity(Label = "Home", MainLauncher = true, LaunchMode = LaunchMode.SingleTop, Icon = "@drawable/Icon")]
    public class MainActivity : BaseActivity
    {
        TcpClient client; // Creates a TCP Client
        NetworkStream stream; //Creats a NetworkStream (used for sending and receiving data)
        byte[] datalength = new byte[4]; // creates a new byte with length 4 ( used for receivng data's lenght)
        DrawerLayout drawerLayout;
        NavigationView navigationView;

        protected override int LayoutResource
        {
            get
            {

                return Resource.Layout.main;
            }
        }
        protected override void OnCreate(Bundle savedInstanceState)
        {

            base.OnCreate(savedInstanceState);



            drawerLayout = this.FindViewById<DrawerLayout>(Resource.Id.drawer_layout);

            //Set hamburger items menu
            SupportActionBar.SetHomeAsUpIndicator(Resource.Drawable.ic_menu);

            //setup navigation view
            navigationView = FindViewById<NavigationView>(Resource.Id.nav_view);
            Button connectButton = FindViewById<Button>(Resource.Id.buttonConnect);
            //handle navigation
            navigationView.NavigationItemSelected += (sender, e) =>
            {
                e.MenuItem.SetChecked(true);

                switch (e.MenuItem.ItemId)
                {
                    case Resource.Id.nav_home_1:
                        ListItemClicked(0);
                        break;
                    case Resource.Id.nav_home_2:
                        ListItemClicked(1);
                        break;
                }

                Snackbar.Make(drawerLayout, "You selected: " + e.MenuItem.TitleFormatted, Snackbar.LengthLong)
                    .Show();

                drawerLayout.CloseDrawers();
            };
            SetContentView(Resource.Layout.main);




            //if first time you will want to go ahead and click first item.
            if (savedInstanceState == null)
            {
                ListItemClicked(0);
            }

            connectButton.Click += (object sender, EventArgs e) =>
            {
                try
                {
                    if (FindViewById<Button>(Resource.Id.buttonConnect).Text == "Connect")
                    {
                        client = new TcpClient("10.0.0.85", 21); //Trys to Connect
                        Toast.MakeText(this, "Connected", ToastLength.Short).Show();
                        //   buttonConnect.Text = "Dis-Connect";
                        //   textReceive.Text = null;
                        //   buttonSend.Enabled = true;
                    }
                    else
                    {
                        //   buttonConnect.Text = "Connect";
                        Toast.MakeText(this, "Dis-Connected", ToastLength.Short).Show();
                        client.GetStream().Close();
                        client.Close();
                    }
                }
                catch (Exception ex)
                {
                    Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
                }
            };
        }


        int oldPosition = -1;

        private void ListItemClicked(int position)
        {
            //this way we don't load twice, but you might want to modify this a bit.
            if (position == oldPosition)
                return;

            oldPosition = position;

            Android.Support.V4.App.Fragment fragment = null;
            switch (position)
            {
                case 0:
                    fragment = Fragment1.NewInstance();
                    break;
                case 1:
                    fragment = Fragment2.NewInstance();
                    break;
            }

            SupportFragmentManager.BeginTransaction()
                .Replace(Resource.Id.content_frame, fragment)
                .Commit();
        }

        public override bool OnOptionsItemSelected(IMenuItem item)
        {
            switch (item.ItemId)
            {
                case Android.Resource.Id.Home:
                    drawerLayout.OpenDrawer(Android.Support.V4.View.GravityCompat.Start);
                    return true;
            }
            return base.OnOptionsItemSelected(item);
        }

        public void clientSend(string msg)
        {
            try
            {
                stream = client.GetStream(); //Gets The Stream of The Connection
                byte[] data; // creates a new byte without mentioning the size of it cuz its a byte used for sending
                data = Encoding.Default.GetBytes(msg); // put the msg in the byte ( it automaticly uses the size of the msg )
                int length = data.Length; // Gets the length of the byte data
                byte[] datalength = new byte[4]; // Creates a new byte with length of 4
                datalength = BitConverter.GetBytes(length); //put the length in a byte to send it
                stream.Write(datalength, 0, 4); // sends the data's length
                stream.Write(data, 0, data.Length); //Sends the real data
            }
            catch (Exception ex)
            {
                Toast.MakeText(this, ex.Message, ToastLength.Short).Show();
            }


        }





    }
}

**为了澄清,我想知道在哪里放置将对象绑定到按钮事件的代码(foo + = foo)。似乎视图没有及时加载以在其当前位置正常运行。 **

1 个答案:

答案 0 :(得分:0)

在您的代码中,请在SetContentView(Resource.Layout.main)

之后立即致电base.OnCreate(savedInstanceState)

有关详细信息,请参阅this similar question