Question: I'm pretty new to android programming. And now, I'm trying to create a ImageView programmatically. But not in the MainActivity, but in a second class I created.

Here's my code:

```
package com.example.joystick;

import android.app.Activity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class Joystick extends Activity{

    ImageView imView;
    RelativeLayout Layout;

public void create(int x, int y, RelativeLayout layout) {
    Layout = layout;
    imView = new ImageView(this);
    imView.setImageResource(R.drawable.joystickknuppel);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.setMargins(x, y, 0, 0);
    imView.setLayoutParams(params);

    Layout.addView(imView);
    }

}

```

If I load the app to my device, it crashes. But if I copy the "create" method into MainActivity, it works well.

Can someone tell me why this happens, and how to fix it?

Thanks a lot!

Answer: 
Replace this method with this code...`onCreateView(...)`

```
@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    LayoutParams params = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT);
    Layout = layout;
imView = new ImageView(this);
imView.setImageResource(R.drawable.joystickknuppel);
params.setMargins(x, y, 0, 0);
imView.setLayoutParams(params);

Layout.addView(imView);

    return view;
}

```

Don't forget to initialize the Layout `Layout`
You must have activity referance to add control on that perticular activity

```
package com.example.joystick;

import android.app.Activity;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;

public class Joystick{

    ImageView imView;
    RelativeLayout Layout;

public void create(Activity act,int x, int y, RelativeLayout layout) {
    Layout = layout;
    imView = new ImageView(act);
    imView.setImageResource(R.drawable.joystickknuppel);
    LayoutParams params = new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
    params.setMargins(x, y, 0, 0);
    imView.setLayoutParams(params);

    Layout.addView(imView);
    }

}

```

if you put 'this' it means it point to your Joystick class which extends Activity but not actually Intent from anywhere.
from which Activity you call create mathod there you have to pass 'this' as Activity parameter.