Is there any way to access a layout\'s view from a non-Activity-derived class? I\'m creating an Accordion class and need to access some of the activity\'s UI elements. I\'
I passed in an instance of one of the Views into the class's constructor.
I'm pretty sure you can just pass an activity as a parameter, e.g.
public void initSouthViews(Activity activity) {
for (int i = 0; i < southScores_.length; ++i) {
southScores_[i] = (EditText) activity.findViewById(10);
}
}
Here is something that might be helpful.
public interface IViewRequest {
public View requestViewByID(int id);
}
public class MyActivity extends Activity {
private IViewRequest viewRequest = new IViewRequest(){
public View requestViewByID(int id){
return findViewById(id);
});
}
public class Accordion(){
private IViewRequest viewRequest;
public Accordion(IViewRequest viewRequest){
this.viewRequest = viewRequest;
}
private View findViewById(int id){
return viewRequest.requestViewByID(id);
}
}
I have never tried something like this. I also don't know if it won't cuase any memory leaks. But it does what you asked :) "Calling findViewById() from outside an activity"
Activity's context is in fact the Activity class itself. Assuming that this object will live inside only one Activity, it should be safe to pass object of type Activity to it. Otherwise, think about reengineering your Accordion class.