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.
FindViewById<T>(Int32)Finds a view that was identified by the id attribute from the XML layout resource.
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.
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.
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 .
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);
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With