Create ImageView programmatically without layout

I am trying to create an ImageView in code by setting an image resource, and then add an ImageView as a child view in the main view. All the examples that I found used a layout for this. But inside the constructor of my view, I cannot figure out how to do this.

Here are the code snippets:

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new CanvasView(this));

    }
}

View:

public class CanvasView extends SurfaceView implements SurfaceHolder.Callback {
    public CanvasView(Context context) {
        super(context);

        SurfaceHolder sh = getHolder();
        sh.addCallback(this);

        ImageView iv = new ImageView(context);
        iv.setImageResource(R.drawable.wand);

        // how to add iv to myself?
    }
}
+4
source share
2 answers

you cannot do this. you need a container for both: for example

public class MainActivity extends Activity {
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(new MyContainer(this));

    }
}

public class MyContainer extends LinearLayout {
  public MyContainer(Context context) {
    addView(new CanvasView(context));
    ImageView iv = new ImageView(context);
    iv.setImageResource(R.drawable.wand);
    addView(iv);
  }
}

remember that if you need to inflate a view directly from the XML file that you need, for MyContainerand a CanvasViewconstructor that takes as parameters ContextandAttributeSet

+1

, , .

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);

    LinearLayout rootLayout = new LinearLayout(getApplicationContext());
    rootLayout.setOrientation(LinearLayout.VERTICAL);

    ImageView imageView = new ImageView(getApplicationContext());
    imageView.setImageResource(R.drawable.sample);

    rootLayout.addView(imageView);

    setContentView(rootLayout);
}
+1

All Articles