MattO
MattO

Reputation: 21

Android text input from XML

I am struggling to learn how XML layouts in android work. I suspect my question has been asked before, but I can't find the answer. I am looking at the APIDemos tutorial that comes with the android SDK. There is a class called AlertDialogSamples in it. I am working with the custom DIAGLOG_TEXT_ENTRY case. I understand how to get the view to be added to the dialog box and how to make the labels and text box change. I cannot understand how to get the user input text from the boxes and do somethign with it. In the lines:

.setPositiveButton(R.string.alert_dialog_ok,
   new DialogInterface.OnClickListener() {
     public void onClick(DialogInterface dialog, int whichButton) {
         /* User clicked OK so do some stuff */
     }

How do I get the user input values of the username and password fields and use them where is says User clicked OK? They should be EditText objects, but I am unfamiliar with how to access these fields since they are formed using XML instead of writting them in JAVA. How do I access XML generated objects?

Thank you

Upvotes: 2

Views: 8933

Answers (2)

SBK
SBK

Reputation: 1585

try this..

String string=editText.getText().toString();

if(!string.equals("")){

Toast.makeText(getApplicationContext(),string,Toast.LENGTH_SHORT).show(); System.out.println(string);

}

Upvotes: 0

Matthew
Matthew

Reputation: 44919

You need to set ids on the EditText fields in your layout xml:

<EditText android:id="@+id/username"
    ... />
<EditText android:id="@+id/password"
    ... />

Then at any time inside your activity you can reference them by:

EditText username = (EditText) findViewById(R.id.username);
EditText password = (EditText) findViewById(R.id.password);

You can get their text by using username.getText(), which returns a CharSequence and can be used like a String.

Upvotes: 1

Related Questions