Declare view elements in another class (context not clear)

偶尔善良 提交于 2019-12-13 04:33:51

问题


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?


回答1:


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.



来源:https://stackoverflow.com/questions/19190281/declare-view-elements-in-another-class-context-not-clear

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!