声明视图元素在其他类(上下文不明确) [英] Declare view elements in another class (context not clear)

查看:150
本文介绍了声明视图元素在其他类(上下文不明确)的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我编程方式创建一个动态UI,并在主类,我创建UI元素,以便以后可以将其添加到 TableLayout 视图。通常我声明它是这样的:

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

其中,这个是上下文。因为我从来没有理解上下文清楚地有人可以告诉我,我怎么能这样声明的TextView 另一个类(如公共静态为例),什么我应该把在上下文中,如果我要在其它的类来声明对此有何看法?

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?

推荐答案

基本上,你必须从你的活动,你调用类新发的上下文。为此,你可以使用构造函数的上下文数据发送到类的新对象。我有一个说明如何创建一个constrctor并使用它的一个例子。
例如,这是你的ExampleClass中:

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.

这篇关于声明视图元素在其他类(上下文不明确)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆