Robotic Reaper
Robotic Reaper

Reputation: 427

How do I make a method in my Java class return findViewById?

I gave my layout file every single element an ID, and in my java class I have a method called locate(). What I'm going to return is:

return findViewById(R.id.star);

But it says cannot resolve symbol findViewById. Also I don't know what should I declare as return type for the method.
So here's what my code look like.

public class Tank {
    public int x;
    public int y;
    public String face;

    public Tank(int xPos,int yPos){
        x=xPos;
        y=yPos;
    }

    public RETURNTYPE locate(){
        return findViewById(R.id.star);
    }
}

I don't know what should be the return type, and findViewById cannot be resolved. I created this class manually(not auto generated).

Upvotes: 1

Views: 93

Answers (3)

Pankaj Kumar
Pankaj Kumar

Reputation: 82948

No need to take Activity or Context for finding the View. As every view which you will locate by findViewById() will be a child of any ViewGroup. So just make it

public <T extends View> T locate(View parentView){
    return parentView.findViewById(R.id.star);
}

Upvotes: 0

user1506104
user1506104

Reputation: 7086

You need proper context when using the findViewById() like so:

public <T extends View> T locate(Activity ctx){
    return ctx.findViewById(R.id.star);
}

Upvotes: 0

Fred
Fred

Reputation: 17085

findViewById is a method of a View, as well of an Activity, hence you'll need an instance of View or of Activity to call it.

Probably it works for you now because you're inside an Activity or a View, but once you move it somewhere else, you'll need to call it on said activity or view, i.e.:

View locate(Activity activity) {
  return activity.findViewById(R.id.star);
}

View locate(View view) {
  return view.findViewById(R.id.star);
}

Notice I'm returning View as the return type? Although this is not incorrect, it's actually not the best and we can make it better.

If you notice, finViewById returns a generic type that extends View. In other words, a concrete view and therefore we could rewrite the methods above like:

<T extends View> T locate(Activity activity) {
  return activity.findViewById(R.id.star);
}

<T extends View> T locate(View view) {
  return view.findViewById(R.id.star);
}

Why is this better? Because you won't have to cast it to the right thing. Without generics you would have to call it like:

TextView t = (TextView) locate();

With generics the code becomes more clean:

TextView t = locate();

PS: Back some time ago, findViewById actually returned View and we were all casting the return type. Nowadays, Google changed it for generics and we don't need to.

Upvotes: 2

Related Questions