2

I create a custom view-MyImageView-to draw a bitmap in it,i use setLayoutParams() to set my view's width and height,but it doesn't work,i use log to track my view's width and height,i found that both of them are 0,why the width and height are not both 300? here's part of my main activity code:

    myCanvas=new MyImageView(CanvasTest3Activity.this,Path);
    LinearLayout.LayoutParams p=new LinearLayout.LayoutParams(300,300);
    myCanvas.setLayoutParams(p);

here's part of my MyImageView 's code:

    protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
    super.onMeasure(widthMeasureSpec, heightMeasureSpec);
    int parentwidth=MeasureSpec.getSize(widthMeasureSpec);
    int parentHeight=MeasureSpec.getSize(heightMeasureSpec);
    int mywidth=(int)(parentHeight*0.5);
    setMeasuredDimension(MeasureSpec.getSize(widthMeasureSpec),mywidth);
    }

1 Answers1

1

You need to get the parent View and use the add method to add your view + your view params. Something like:

"ParentViewInstance.add(this_is_my_child_view, this_is_the_layout_params_for_my_child_view)"

This means that the type of the LayoutParams of your child view, should be the same type as the ParentView LayoutParams. Take a look at this answers for code samples.

Community
  • 1
  • 1
hovanessyan
  • 30,580
  • 6
  • 55
  • 83
  • LinearLayout layout=new LinearLayout(this); ...layout.addView(myCanvas,p); but finally there appears two view in my screen ...i wanna ask that if i use addview method , should I add view in xml,too? – facebook-100000298961430 Dec 17 '11 at 14:40
  • if your view is created programmatically, you don't have to add it in the xml layout (you just need to think in advance, how to include it in the already existing layout). – hovanessyan Dec 17 '11 at 16:31