Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 322
SHAI Avatar asked Jan 07 '23 23:01

SHAI


2 Answers

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);
like image 154
2Dee Avatar answered Jan 18 '23 20:01

2Dee


Best way to do so is,

public class MyCustomView extends TextView {
    private MainActivity mActivity;

    public void setActivity(MainActivity activity) {
        mActivity = activity;
    }

    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();
    }
}

Instantiate,

customView = (MyCustomView) findViewById(R.id.view2);
customView.setActivity(this);

Access variable inside functions in MyCustomView,

mActivity.myVar = 10;
like image 33
Sazzad Hissain Khan Avatar answered Jan 18 '23 20:01

Sazzad Hissain Khan