在android中创建了新类但无法弄清楚上下文

时间:2012-09-16 21:21:30

标签: android

我在android中创建了一个新类,在实例化时创建LinearLayouts。但是,我无法弄清楚要放在new LinearLayout(context)括号中的上下文。有人可以解释一下吗? (我已经尝试过在环境中阅读所有内容)

我假设我不需要在我的课程中扩展活动

public class NewLayouts {
...
newParentLayout = new LinearLayout(getApplicationContext()); //<--eclipse warns of error here saying not a valid context
newParentLayout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.MATCH_PARENT));
newParentLayout.setOrientation(LinearLayout.VERTICAL);
TextView monthDisplay = new TextView(getApplicationContext()); //<--eclipse warns of error here saying not a valid context
...
}

我的主要活动:

public class MainActivity extends Activity {

public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        NewLayouts Sample = new NewLayouts(1,2); //variables required in my constructor for new Layouts
        setContentView(Sample.newParentLayout);
}

2 个答案:

答案 0 :(得分:1)

NewLayouts的构造函数更改为......

public NewLayouts(Context ctx, int X, int Y) {...}

...然后使用ctx作为Context中的NewLayouts来创建Views

Activity中,然后执行以下操作......

NewLayouts Sample = new NewLayouts(this, 1, 2);

这会将Activity's自己的Context传递给NewLayouts构造函数。

答案 1 :(得分:0)

尝试new LinearLayout(this)new LinearLayout(newLayouts.this)