Android: How to get a view given an activity inside a normal class?

android, android-layout, layout, view

Solution

Regarding the NullPointerException (which you should add to the question), always make sure you've called setContentView() in your Activity before trying to access a View defined in XML. Example usage:

public class MainActivity extends Activity {

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ...
    }

    ...
}

Then, somewhere,

        ViewGroup group = (ViewGroup) context.findViewById(R.id.group); // In your example, R.id.my_view

The reason you need to have called setContentView() is that before it's called, your View(Group) doesn't exist. Because findViewById() is unable to find something that doesn't exist, it returns null.

Problem

I have a normal class (not an activity). Inside that class, I have a reference to an activity. Now I want to access a view (to add a child) contained in the layout xml of that activity. I don't know the name of the layout file of that activity. I only know the ID of the view, which I want to access (for example: R.id.my_view). How can I do that?

Original source