Android: Accessing other views from inside a custom view using findViewById().

If you attempt to call findViewById() on the ID of a view that is not from the Activity that holds the view, findViewById() returns null. I’ve seen a lot of solutions posted for attempting to access a View from outside the activity that created it. Most of them involve inflating the original view and going from there. I can’t speak to whether or not that actually works (I do not believe they will), but I can offer an alternative, more attractive solution.

For this option, you will need a reference to the activity that holds the view you want to modify, this is usually given to you in the form of a Context object passed into your constructor. You can save that context in a member variable, and from there call context.findViewById(), which will return the view you want.

public class SomeClass extends View{
     Context context;
     ...

     public SomeClass(Context context, AttributeSet attrSet){
          super(context,attrSet);
          this.context=context;
          ...
     }

     public void someFunction(){
          TextView t=(TextView)context.findViewById(R.id.someTextView);
          ...
     }
}

In many cases, it will be preferable to not access the View directly, and instead add a public function to the Activity that actually holds the view. This way many other classes will be able to access the same function, which is very often necessary. Then, in order to access that function, you cast the Context to the Activity Class that holds the view:

public class SomeClass extends View{
     Context context;
     ...

     public SomeClass(Context context, AttributeSet attrSet){
          super(context,attrSet);
          this.context=context;
          ...
     }

     public void someFunction(){
          ((MyActivity)context).manipulateSomeViews();
          ...
     }
}

I would say the second example is a much more elegant solution as it keeps the logic controlling a View inside the class that holds it. But, as with everything, you’ll likely find many exceptions.

Leave a Reply