I've got a few questions about edittext..
I'm trying to create a login screen on Android. I'm taking in a username and a password and then sending the results to another method. I've just got a few questions about it...
1) If I have two edittext's and the user enters values in both and then hits a "login" button, I want the button to take the values that were entered in the 2 edittext boxes, convert and save them 开发者_如何学Pythonto a string and then pass them to a function. I'm unsure how I'd construct this button. The problem I'm having is making it a string I'm currently doing this..
String user = edittext.getText();
But that doesn't seem to work. Also I'm unsure what way Android saves Edittext inputs.. Will it just automatically save it to the string once the user is no longer working out of the box? e.g will...
public boolean onKey(View v, int keyCode, KeyEvent event) {
String user = edittext.getText();
}
work? If not how would I define it?
Thanks.
You have to subscribe for the onClick event of the button, then simple get the text from the EditText
You don't need to run code on the onKey event of EditText
(Button) findViewById(R.id.btnName)).setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
//called when you press the button
String user =((EditText) findViewById(R.id.txtUser)).getText().toString();
String password =((EditText) findViewById(R.id.txtPassword)).getText().toString();
// do the rest of the job
}
});
Essentially this is what you want to do
String userName = "";
String password = "";
EditText userEdit = (EditText)findViewById(R.id.useredit);
EditText passEdit = (EditText)findViewById(R.id.passedit);
Button okButton = (Button)findViewById(R.id.okButton);
okButton.setOnClickListener(new OnClickListener() {
@Override
public void onClick(View v) {
userName = userEdit.getText().toString();
password = passEdit.getText().toString();
}
});
Instead of using onKeyDown(...)
you should register an on-click listener for your button and define its behavior there. Strangely enough you actually have to put .toString()
after .getText()
in order to store the text.
I would also suggest making all of your views (fields, buttons, images, ect) member variables so your references are persistent.
精彩评论