Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Create ImageView programmatically without Layout

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

Here are the code snippets:

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

    }
}

The 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?
    }
}
like image 821
Matthias Avatar asked Oct 21 '22 19:10

Matthias


1 Answers

you can not do that this way. you need a container for both: For instance

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 the view directly from a xml file you need, for both MyContainer and CanvasView the constructor thats takes as parameters Context and AttributeSet

like image 133
Blackbelt Avatar answered Oct 24 '22 11:10

Blackbelt