2

How can I pass findViewById as parameter?

I would like create method:

public void makeText() {
    String random = randomize(); //example...
    TextView textView = (TextView) findViewById(R.id.textView);
    textView.setText(randomText);
}

But of course this method don't have function findViewById. Method makeText is outside Activity and Fragment classes.

faraz khonsari
  • 1,924
  • 1
  • 19
  • 27
fapevasoz
  • 39
  • 1
  • 4
  • You should pass an instance of `TextView` as a parameter. And then you can do `yourTextView.setText(randomText)` – Dima Kozhevin Oct 14 '17 at 12:47
  • 3
    Possible duplicate of [findViewById in non-Activity class](https://stackoverflow.com/questions/25807205/findviewbyid-in-non-activity-class) – Akhilesh Awasthi Oct 14 '17 at 12:48

3 Answers3

8

you should pass activity instance to your class or method.

public void makeText(Activity activity) {
    String random = randomize(); //example...
    TextView textView = (TextView) activity.findViewById(R.id.textView);
    textView.setText(randomText);
}
faraz khonsari
  • 1,924
  • 1
  • 19
  • 27
3

Passing activity's instance as a parameter is an antipattern and begging for memory leaks.

Rule of thumbs is: If you want to manipulate view, do it on UI layer (Activity/Fragment/Custom View etc), but don't pass them any further.

So if you want to edit text, inflate this view inside activity/fragment/whatsoever and pass to it a new value.

KrzysztofB
  • 101
  • 11
2

First of all it is bad idea to edit controls properties beyond activity or fragment class. Passing context objects as Activity is also not the best idea, but I you must do it pass as argument ViewGroup which is the root of your view and call findViewById on it.

Personal I would recommend pass to method View you want to edit.

Karol Kulbaka
  • 1,136
  • 11
  • 21
  • So how can I do it? I don't want repet code. In several activities I have this code, so I would like have it in one place. – fapevasoz Oct 14 '17 at 12:57
  • Make base Activity/Fragment to inherit from it. After all I still don't see any case to make such global methods. – Karol Kulbaka Oct 14 '17 at 13:42