MadMan
MadMan

Reputation: 1

Using findViewById in an external class

My app has many elements in the layout (well over 100) and declaring all of them in the MainActivity so as to access them is making my MainActivity class difficult to read and debug. So I created a new class to handle working with the display elements:

public class DisplayElementHandler extends Activity{
private EditText txtUserID;
    public void Initialise(){ //initialise all display elements
        txtUserID = (EditText) findViewById;
    }
}

However the findViewById does not work as I expected it to.

I am an Android Studio/Java newbie and this one has me stumped - can anyone help please?

Upvotes: 0

Views: 3484

Answers (2)

emerssso
emerssso

Reputation: 2386

You want to delegate work done by your Activity to your Handler class. Extending Activity makes the Handler it's own activity (another screen), which isn't really what you want here. It should interact with your existing Activity.

This can be achieved a number of ways, but I would pass a reference to your activity to your Handler in the constructor, like so:

 public class DisplayElementHandler {
      private Activity activity;
      public DisplayElementHandler(Activity activity) {
           this.activity = activity;
      }

      public void Initialise(){ //initialise all display elements
           txtUserID = (EditText) activity.findViewById(...);
      }
 }

And then in your Activity:

 public void onCreate(Bundle b) {
      super.onCreate(b);
      new DisplayElementHandler(this).Initialise();
 }

You may also want to pass the R.id reference to the view into the Handler as part of the constructer as well.

Upvotes: 2

JohannesF
JohannesF

Reputation: 30

Well, 100 elements in one class is a lot. Maybe think about it and find a way to reduce that :D

You try to call your elements from an external class, so you have to tell in which class your elements are. The way you did just searches in the current class.

Upvotes: 0

Related Questions