Reputation: 309
I am creating a dynamic UI programatically and in main class I am creating UI element so that I can later add it to TableLayout
view. Normally I declare it like this:
TextView tw_1_2 = new TextView(this);
where this
is the context. Since I never get to understand context clearly can someone tell me how can I declare this TextView
in another class (as public static for example) and what should I put in context if I want to declare this view in some other class?
Upvotes: 0
Views: 549
Reputation: 1037
Basically you have to send context from your activity that you call new class. for this purpose you can use constructor to send context data to the new object of class. I have an example that show how to create a constrctor and use it. for example this is your ExampleClass:
public class ExampleClass{
private final Context context;
public ExampleClass(Context context) {
this.context = context;
}
}
and in your Activity Class do this:
ExampleClass ex1 = new ExampleClass(MainActivity.this);
and if you want use your class as static you must only define your class and context variable as static without constructor and set context equals your context. I hope this help you.
Upvotes: 1