Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

using findviewbyid in a class that does NOT extend Activity in android

I have a class that is currently extending Activity and I have methods like findViewById, ArrayAdapter etc. I want to turn it into an independent class but all the above methods become undefined. What is the problem? Shouldn't importing the classes be enough? For eg, I import android.view.View for findViewById but it still makes no difference. Please advise.

like image 686
Namratha Avatar asked Nov 30 '11 09:11

Namratha


People also ask

What is the purpose of findViewById () method in Android?

FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.

How do I use findViewById on Android?

Step 1 − Create a new project in Android Studio, go to File ⇒ New Project and fill all required details to create a new project. Step 2 − Add the following code to res/layout/activity_main. xml.

What does findViewById method do?

The findViewById() method is a method of Android's View and Activity classes. The method is used to find an existing view in your XML layout by its android:id attribute. The same can be done for any valid Android View object, such as a Button or a CheckBox view.

What does findViewById return?

findViewById returns an instance of View , which is then cast to the target class. All good so far. To setup the view, findViewById constructs an AttributeSet from the parameters in the associated XML declaration which it passes to the constructor of View . We then cast the View instance to Button .


1 Answers

you should pass the instance of your Activity to your Second Class on the constructor like this :

In your Activity Instanciate your Class like this :

MyClass instance = new MyClass(this); 

And in your second Class , the constructor will be like this :

public class MyClass {  public Activity activity;  //.... other attributes   public MyClass( Activity _activity){     this.activity = _activity; //other initializations...  } } 

and then when you want to use the findViewById() method , you can do like this :

EditText txt = (EditText)this.activity.findViewById(R.id.txt); 
like image 153
Houcine Avatar answered Oct 16 '22 02:10

Houcine