Terence Chow
Terence Chow

Reputation: 11153

created new class in android but can't figure out context

I created a new class in android that creates LinearLayouts when instantiated. However I can't figure out the context to put in the brackets of: new LinearLayout(context). Can someone shed some light? (I've already tried reading everything i can on contexts)

I'm assuming I don't need to extend Activity in my class

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
...
}

My main activity:

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

Upvotes: 2

Views: 82

Answers (2)

Squonk
Squonk

Reputation: 48871

Change the constructor of NewLayouts to be something like...

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

...then use ctx as the Context in NewLayouts for creating the Views.

In the Activity then do the following...

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

That will pass the Activity's own Context into NewLayouts constructor.

Upvotes: 1

Juan Manuel
Juan Manuel

Reputation: 239

try new LinearLayout(this) or new LinearLayout(newLayouts.this)

Upvotes: 0

Related Questions