Skip to content Skip to sidebar Skip to footer

How To Draw A Imageview In The Middle Of The Screen? (programatically)

I want to draw a simple ImageView in the middle of the screen, horizontally and vertically. But i want to do it without using XML files, i need to do it programatically. I tryed wi

Solution 1:

It works for me like this:

package pete.android.study;

import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.view.Display;
import android.view.WindowManager;
import android.widget.ImageView;
import android.widget.RelativeLayout;
import android.widget.RelativeLayout.LayoutParams;


publicclassMainextendsActivity {

    /*
     * (non-Javadoc)
     * @see android.app.Activity#onCreate(android.os.Bundle)
     */@OverridepublicvoidonCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        ImageViewARImage=newImageView(getApplicationContext());
        ARImage.setImageResource(R.drawable.icon);
        RelativeLayoutrl=newRelativeLayout(this);
        Displaydisplay= ((WindowManager) getSystemService(Context.WINDOW_SERVICE)).getDefaultDisplay();
        intw= display.getWidth();
        inth= display.getHeight();
        RelativeLayout.LayoutParamsposition=newRelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
        ARImage.setLayoutParams(position);  

        position.addRule(RelativeLayout.CENTER_IN_PARENT);
        rl.addView(ARImage, position);  
        setContentView(rl); 
    }

}

Solution 2:

Try to use

position.leftMargin = (int)(w/2 - whalf);position.topMargin  = (int)(h/2 - hhalf);

where whalf and hhalf are halfs of your image parameters.

Solution 3:

I don't think you can set the left and top margin like that:

position.leftMargin = (int)(w/2);position.topMargin  = (int)(h/2);

Try setting the margins like this:

position.setMargins((int)(w/2), (int)(h/2), 0, 0); // left, top, right, bottom

Solution 4:

Knowing that it is inside of RelativeLayout, you can place it in center of this layout:

  RelativeLayout.LayoutParamslp=newRelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
  lp.addRule(RelativeLayout.CENTER_IN_PARENT);
  rl.addView(ARImage, lp);

Post a Comment for "How To Draw A Imageview In The Middle Of The Screen? (programatically)"