Skip to content
Advertisement

Getting MainActivity context in CustomView class

I have 2 classes: MainActivity and CustomView. I have an XML layout with this CustomView.

I want to access all my MainActivity variables from my CustomView class and also to modify them, I tried to get the context but it didn’t work.

MainActivity class:

 MyCustomView customV;
 int myVar;


@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.start_page);
    customV = (MyCustomView) findViewById(R.id.view2);
    myVar = 5;
    }

MyCustomView class:

public class MyCustomView extends TextView {

public MyCustomView(Context context) {
    super(context);
    init();
}

public MyCustomView(Context context, AttributeSet attrs) {
    super(context, attrs);
    init();
}

public MyCustomView(Context context, AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);
    init();
}

context.myVar = 7  //this is what I'm trying to do... 

I also tried getContext which didn’t work.

Advertisement

Answer

By trying to access variables from your Activity directly in your TextView subclass, you introduce tight coupling between you subclass of Actity and your custom TextView, which essentially hinders the reusability of your custom TextView because it can then only be used in that type of Activity, using it in another layout would break everything. Basically, I would say it’s bad design and would not recommend that approach.

You could simply add a method to your custom TextView, and use the variable there :

public class MyCustomView extends TextView {

    // your code

    public void setVariable(int myInt){
        //use the int here, either set a member variable 
        //or use directly in the method
    }
}

and in your Activity

customV = (MyCustomView) findViewById(R.id.view2);
customV.setVariable(5);
User contributions licensed under: CC BY-SA
10 People found this is helpful
Advertisement