Question

I would like to have an image on android that appears only when I click a button. So I created it in an onClick method, and set its ressource and position with the following code :

public void createAddButton() {
    //create the image
    ImageView imageView = new ImageView(this);
    //setting image resource
    imageView.setImageResource(R.drawable.add_16);
    //setting image position : width and height
    imageView.setLayoutParams(
            new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT) );
}

But this only allows to define width and height of the image. If I want to define other layout parameters (android:layout_gravity or android:marginLeft for example, what should I do ?

Était-ce utile?

La solution

LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
  LinearLayout.LayoutParams.MATCH_PARENT, 
  LinearLayout.LayoutParams.WRAP_CONTENT);
lp.gravity = Gravity.CENTER;
lp.bottomMargin = ...
lp.leftMargin = ...
lp.rightMargin = ...
lp.topMargin = ...

imageView.setLayoutParams(lp);

Autres conseils

You have to use LayoutParams object to access those layout properties as below...

    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    params.gravity = Gravity.CENTER;
    params.leftMargin = 10;

    imageView.setLayoutParams(params);
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top