So I guess It was a simple as using a getText() to retrieve the information 🙂
Here is how it ended:
public void getToast(View v) {
EditText et = (EditText) findViewById(R.id.userText);
String toastText = et.getText().toString();
if (toastText == "" || toastText == null) {
Toast.makeText(this, "This is a nice toast!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show();
}
}
I have created an EditText View on the main layout file. This is referenced to with the userText identifier. As it is an EditText field, the user is able to modify the text within it at any moment; what I am trying to accomplish is to retrieve the text the user has entered at the moment they tap on the button identified as getToast, and then display it as a Toast.
I am using the Resources class at the moment (my first guess?) to retrieve the String stored under toastText but this is useless, as it is extracting the text stored in the main.xml – which is empty, as I declared no “android:text” attribute for that view, instead I used an “android:hint” to tell the user to enter the text.
I had read about intents, but that kind of makes sense if I was to send the String to another activity, not within the same one. I had thought of it as a simple task, but it is consuming more time that I had hope 😛
BTW:
The getToast method is defined as an “android:OnClickMethod” for a button created on the XML. It will work with any other string of text.
Any ideas?
package com.testlabs.one;
import android.app.Activity;
import android.content.res.Resources;
import android.os.Bundle;
import android.view.View;
import android.widget.Toast;
public class initialui extends Activity {
/** Called when the activity is first created. */
@Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
}
public void getToast(View v) {
Resources myResources = getResources();
String toastText = myResources.getString(R.string.toast);
if (toastText == "" || toastText == null) {
Toast.makeText(this, "This is a nice toast!", Toast.LENGTH_SHORT).show();
}
else {
Toast.makeText(this, toastText, Toast.LENGTH_SHORT).show();
}
}
}
You simply call the function
getText()on the TextView.Example:
This code will display a toast with the text in your EditText when it is available and the default text in the
toastresource when nothing was entered.