Reputation: 11
I am creating an expert system engine with a custom scripting engine, and some of the commands are integrated with the main xml gui. As an example, there is a 'respond' command that accepts strings and sets them in an EditText. The respond command is essential to the functionality of the app, but I cannot access the EditText with findViewById because the command routine resides in another class. Even if it is bad form, how can I access GUI elements from other classes?
Thank you.
Upvotes: 1
Views: 2654
Reputation: 3152
I had this same problem. My code in my activity had too much code, and I wanted to create external classes to do some of the processing in there. However, one process included using an EditText
, and you can't instantiate that in a class that has no UI. So the easiest solution is to make your EditText myEditText
variable public
and static
in the activity, and then when you use it in your external class, just use dot notation with the original activity it came from, and it should work. The static
keyword is what makes it a global variable, accessible by other classes/activities.
public static EditText myEditText;
// put this in your Activity
ActivityName.myEditText.someMethod();
// use of EditText in your external class
Upvotes: 0
Reputation: 37905
Provide the EditText object to 'the other class' by using a custom method (like public void setEditText(EditText myEditText)
, or something similar), or as a parameter in its constructor (depending on your situation).
Another possibility is to send the complete Activity that defined the EditText, so you can use findViewById()
to grab the EditText. But I would not recommend it (bad practice, I think) unless you have lots of objects that you need to access.
Upvotes: 0
Reputation: 86948
how can I access GUI elements from other classes?
If the other class is an Activity, you cannot. You should pass the EditText's contents in an Intent or by some other means.
If the other class isn't an Activity, simply make the EditText a public field variable. Or you can pass this other class a reference to your Activity or the root View and use methods like findViewById()
without much fuss.
Upvotes: 1