2

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

我假设我不需要在课堂上扩展 Activity

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

2 回答 2

1

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

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

...然后ctx用作创建Context.NewLayoutsViews

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

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

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

于 2012-09-16T21:48:58.890 回答
0

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

于 2012-09-16T21:30:22.480 回答