Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Calling findViewById() from outside an activity

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'm passing in the activity's context to my accordion class's constructor, but the findViewById API is only available from the Activity class. I also don't want to pass in an instance of my activity since that seems to be frowned upon due to potential memory leaks.

like image 858
Phillip Avatar asked Sep 12 '11 20:09

Phillip


People also ask

How do I use findViewById on Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .

What is android view view?

View is a basic building block of UI (User Interface) in android. A view is a small rectangular box that responds to user inputs. Eg: EditText, Button, CheckBox, etc. ViewGroup is an invisible container of other views (child views) and other ViewGroup.

What is view tag in android?

Tags are essentially an extra piece of information that can be associated with a view. They are most often used as a convenience to store data related to views in the views themselves rather than by putting them in a separate structure. Reference: http://developer.android.com/reference/android/view/View.html.


1 Answers

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);
    }
}
like image 157
Nicco Simone Avatar answered Oct 13 '22 15:10

Nicco Simone