2017-06-21 48 views
1

花了这么多时间找到这么简单的东西后,最后我必须去这里,需要有人帮助我。在EditText中的getValue - XAMARIN ANDROID

如何从Xamarin中的EditText获取值,因为它总是返回null。

这里是我的代码:

Button loginBtn; 
EditText username; 
EditText password; 
string user; 
string pass; 
    protected override void OnCreate(Bundle savedInstanceState) 
     { 
      RequestWindowFeature(Android.Views.WindowFeatures.NoTitle); 
      base.OnCreate(savedInstanceState); 
      // Create your application here 
      SetContentView(Resource.Layout.LoginForm); 

      loginBtn = FindViewById<Button>(Resource.Id.login); 
      username = (EditText)FindViewById(Resource.Id.userName); 
      password = (EditText)FindViewById(Resource.Id.password); 

      user = username.Text.ToString(); 
      pass = password.Text.ToString(); 


      loginBtn.Click += (object sender, EventArgs e) => 
      { 

       Toast.MakeText(this, user + " : " + pass, ToastLength.Long).Show(); 
      }; 
     } 

回答

1

你必须移动按钮单击事件里面的代码,因为你editexts在OnCreate方法,他们得到null值作为OnCreate是被称为第一种方法(除如果你在xml代码中给它们一些值),并且你永远不会再次调用你的editexts来为它们分配用户输入值。所以我认为这将解决您的问题:

loginBtn.Click += (object sender, EventArgs e) => 
     { 
      user = username.Text.ToString(); 
      pass = password.Text.ToString(); 
      Toast.MakeText(this, user + " : " + pass, ToastLength.Long).Show(); 
     }; 
+0

谢谢@Yupi,你的建议是正确的。 –