2017-06-21 106 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,你的建議是正確的。 –