Setting margins for an imageview dynamically

烈酒焚心 提交于 2019-12-11 09:21:48

问题


may I know how to set margin in imageview dynamically?


回答1:


You're probably looking for something like this: http://developer.android.com/reference/android/view/View.html#setLayoutParams(android.view.ViewGroup.LayoutParams)

Note this part of the method description though:

These supply parameters to the parent of this view specifying how it should be arranged

Which means that if you have an ImageView inside of a LinearLayout, you need to supply the method with LinearLayout.LayoutParams, like this:

ImageView image = new ImageView(this);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
params.setMargins(1, 1, 1, 1);
image.setLayoutParams(params);

And then you just call setMargins or set the specific leftMargin, bottomMargin etc. properties of the LayoutParams.




回答2:


create layout dynamically and set its parameter as setmargin() will not work directly on an imageView

ImageView im;
im = (ImageView) findViewById(R.id.your_image_in_XML_by_id);
 RelativeLayout.LayoutParams layout = new RelativeLayout.LayoutParams(im.getLayoutParams());
                        layout.setMargins(counter*27, 0, 0, 0);//left,right,top,bottom
                        im.setLayoutParams(layout);
                        im.setImageResource(R.drawable.yourimage)


来源:https://stackoverflow.com/questions/7085169/setting-margins-for-an-imageview-dynamically

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!