【问题标题】:How to set margin of ImageView using code, not xml如何使用代码而不是 xml 设置 ImageView 的边距
【发布时间】:2011-03-25 20:54:12
【问题描述】:

我想在我的布局中添加未知数量的 ImageView 视图并带有边距。在 XML 中,我可以像这样使用layout_margin

<ImageView android:layout_margin="5dip" android:src="@drawable/image" />

ImageView.setPadding(),但没有ImageView.setMargin()。我认为它与ImageView.setLayoutParams(LayoutParams) 类似,但不确定要添加什么内容。

有人知道吗?

【问题讨论】:

    标签: android margin imageview


    【解决方案1】:

    android.view.ViewGroup.MarginLayoutParams 有一个方法setMargins(left, top, right, bottom)。直接子类是:FrameLayout.LayoutParamsLinearLayout.LayoutParamsRelativeLayout.LayoutParams

    使用例如LinearLayout:

    LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
    lp.setMargins(left, top, right, bottom);
    imageView.setLayoutParams(lp);
    

    MarginLayoutParams

    这会以像素为单位设置边距。要扩展它,请使用

    context.getResources().getDisplayMetrics().density
    

    DisplayMetrics

    【讨论】:

    • 请注意,这在 PIXELS 中设置边距大小,与此问题的 xml 中的 dpi 单位不同。
    • 我们如何使用 dpi 值而不是像素?
    • 您可以使用 context.getResources().getDisplayMetrics().density developer.android.com/reference/android/util/… 来缩放 px 值
    • 请注意,FrameLayout.LayoutParams 和其他可能存在问题:stackoverflow.com/questions/5401952/…
    • 如果我们只想设置图像视图的下边距,即android:layout_centerHorizontal = "true"android:layout_alignParentBottom = "true",我可以用什么方法来完成这个?
    【解决方案2】:
        image = (ImageView) findViewById(R.id.imageID);
        MarginLayoutParams marginParams = new MarginLayoutParams(image.getLayoutParams());
        marginParams.setMargins(left_margin, top_margin, right_margin, bottom_margin);
        RelativeLayout.LayoutParams layoutParams = new RelativeLayout.LayoutParams(marginParams);
        image.setLayoutParams(layoutParams);
    

    【讨论】:

    • 最后两行是怎么回事?将边距参数克隆到另一个参数变量中?我可以确认它是必需的:)
    • 如果我们只想设置图像视图的下边距,即android:layout_centerHorizontal = "true"android:layout_alignParentBottom = "true",我可以用什么方式来完成这个?
    • layoutparams.addRule(RelativeLayout.CENTER_HORIZONTAL);
    • 需要创建另一个布局参数。谢谢:)
    【解决方案3】:

    Kevin 的代码创建了多余的MarginLayoutParams 对象。更简单的版本:

    ImageView image = (ImageView) findViewById(R.id.main_image);
    RelativeLayout.LayoutParams lp = new RelativeLayout.LayoutParams(image.getLayoutParams());
    lp.setMargins(50, 100, 0, 0);
    image.setLayoutParams(lp);
    

    【讨论】:

    • 奇怪的是,然后我得到“无法解析方法 setmargins()”,这就是我搜索这个问题并登陆这里的原因。
    【解决方案4】:

    示例代码在这里,非常简单

    LayoutParams params1 = (LayoutParams)twoLetter.getLayoutParams();//twoletter-imageview
                    params1.height = 70;
                    params1.setMargins(0, 210, 0, 0);//top margin -210 here
                    twoLetter.setLayoutParams(params1);//setting layout params
                    twoLetter.setImageResource(R.drawable.oo);
    

    【讨论】:

      【解决方案5】:

      如果你想在 dp 中指定边距,你可以使用这个方法:

      private void addMarginsInDp(View view, int leftInDp, int topInDp, int rightInDp, int bottomInDp) {
          DisplayMetrics dm = view.getResources().getDisplayMetrics();
          LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT);
          lp.setMargins(convertDpToPx(leftInDp, dm), convertDpToPx(topInDp, dm), convertDpToPx(rightInDp, dm), convertDpToPx(bottomInDp, dm));
          view.setLayoutParams(lp);
      }
      
      private int convertDpToPx(int dp, DisplayMetrics displayMetrics) {
          float pixels = TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, dp, displayMetrics);
          return Math.round(pixels);
      }
      

      【讨论】:

        【解决方案6】:

        动态创建布局并将其参数设置为 setmargin() 不会直接在 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)
        

        【讨论】:

          【解决方案7】:

          对我来说这很有效:

          int imgCarMarginRightPx = (int)TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, definedValueInDp, res.getDisplayMetrics());
          
          MarginLayoutParams lp = (MarginLayoutParams) imgCar.getLayoutParams();
          lp.setMargins(0,0,imgCarMarginRightPx,0);
          imgCar.setLayoutParams(lp);
          

          【讨论】:

            【解决方案8】:

            上述所有示例实际上会REPLACE视图中已经存在的任何参数,这可能不是我们所希望的。下面的代码只会扩展现有的参数,而不是替换它们:

            ImageView myImage = (ImageView) findViewById(R.id.image_view);
            MarginLayoutParams marginParams = (MarginLayoutParams) image.getLayoutParams();
            marginParams.setMargins(left, top, right, bottom);
            

            【讨论】:

            • 这是此列表中第一个对我有用的解决方案。其他人搞砸了我在 XML 中设置的其他参数,包括用于定位的 RelativeLayout 参数。
            【解决方案9】:

            我简单地使用这个并且效果很好:

            ImageView imageView = (ImageView) findViewById(R.id.image_id);
            RelativeLayout.LayoutParams layoutParams = (RelativeLayout.LayoutParams) imageView.getLayoutParams();
            layoutParams.setMargins(left, top, right, bottom);
            imageView.setLayoutParams(layoutParams);
            

            setMargins() 的单位是像素而不是 dp。如果您想在 dp 中设置边距,只需在 values/dimens.xml 文件中创建您的尺寸,例如:

            <resources>
                <dimen name="right">16dp</dimen>
                <dimen name="left">16dp</dimen>    
            </resources>
            

            并像这样访问:

            getResources().getDimension(R.dimen.right);
            

            【讨论】:

              【解决方案10】:

              如果您想更改 imageview 边距但保持所有其他边距不变。

              1. 在这种情况下获取图像视图的 MarginLayoutParameters:myImageView

                 MarginLayoutParams marginParams = (MarginLayoutParams) myImageView.getLayoutParams();
                
              2. 现在只需更改您要更改的边距,但保持其他边距不变:

                 marginParams.setMargins(marginParams.leftMargin, 
                                         marginParams.topMargin, 
                                         150, //notice only changing right margin
                                         marginParams.bottomMargin); 
                

              【讨论】:

                【解决方案11】:

                在某些情况下,使用与此类似的方法可能会为您省去一些麻烦。 如果您对边距进行了两次编程修改,则检查是否已经设置了一些 layoutParams 会更安全。如果已经有一些边距,应该增加它们而不是替换它们:

                public void addMargins(View v, int left, int top, int right, int bottom) {
                    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams) v.getLayoutParams();
                    if (params == null)
                        params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
                                                               ViewGroup.LayoutParams.WRAP_CONTENT);
                    int oldLeft = params.leftMargin;
                    int oldTop = params.topMargin;
                    int oldRight = params.rightMargin;
                    int oldBottom = params.bottomMargin;
                    params.setMargins(oldLeft + left, oldTop + top, oldRight + right, oldBottom + bottom);
                    v.setLayoutParams(params);
                }
                

                【讨论】:

                  【解决方案12】:

                  如果你使用 kotlin,这可以通过创建扩展函数来简化

                  fun View.setMarginExtensionFunction(left: Int, top: Int, right: Int, bottom: Int) {
                    val params = layoutParams as ViewGroup.MarginLayoutParams
                    params.setMargins(left, top, right, bottom)
                    layoutParams = params
                  }
                  

                  现在你只需要一个视图,这个扩展功能可以在任何地方使用。

                  val imageView = findViewById(R.id.imageView)
                  imageView.setMarginExtensionFunction(0, 0, 0, 0)
                  

                  【讨论】:

                  • 这适用于leftright 边距,但如果您有相对边距(startend),它就不起作用。我用你的代码的“改进”版本写了一个要点:gist.github.com/Grohden/f40c53bf86c5395638f7a44bf90e732dsetMarginsRelative 函数) - 你能把它包括在你的答案中吗?
                  【解决方案13】:

                  这是一个在左、上、右、下添加 8px 边距的示例。

                  
                  ImageView imageView = new ImageView(getApplicationContext());
                  
                  ViewGroup.MarginLayoutParams marginLayoutParams = new ViewGroup.MarginLayoutParams(
                      ViewGroup.MarginLayoutParams.MATCH_PARENT,
                      ViewGroup.MarginLayoutParams.WRAP_CONTENT
                  );
                  
                  marginLayoutParams.setMargins(8, 8, 8, 8);
                  
                  imageView.setLayoutParams(marginLayoutParams);
                  
                  

                  【讨论】:

                    【解决方案14】:

                    2020 年的答案:

                    dependencies {
                        implementation "androidx.core:core-ktx:1.2.0"
                    }
                    

                    并在您的代码中简单地调用它

                    view.updateLayoutParams<ViewGroup.MarginLayoutParams> {
                       setMargins(5)
                    }
                    

                    【讨论】:

                      【解决方案15】:

                      在 Kotlin 中你可以用更愉快的方式编写它

                      myView.layoutParams = LinearLayout.LayoutParams(
                                      RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT
                                  ).apply {
                                      setMargins(12, 12, 12, 12)
                                  }
                      

                      【讨论】:

                        【解决方案16】:

                        我们可以创建 Linear LayoutParams 并使用 resources.getDimensionPixelSize 作为 dp 值。

                            val mContext = parent.context
                            val mImageView = AppCompatImageView(mContext)
                            mImageView.setBackgroundResource(R.drawable.payment_method_selector)
                        
                            val height = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_height)
                            val width = mContext.resources.getDimensionPixelSize(R.dimen.payment_logo_width)
                            val padding = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small_tiny)
                            val margin = mContext.resources.getDimensionPixelSize(R.dimen.spacing_small)
                        
                            mImageView.layoutParams = LinearLayout.LayoutParams(width, height).apply {
                                setMargins(margin, margin, 0, 0)
                            }
                            mImageView.setPadding(padding, padding, padding, padding)
                        

                        【讨论】:

                          猜你喜欢
                          • 1970-01-01
                          • 2011-09-27
                          • 1970-01-01
                          • 2012-05-02
                          • 2012-02-24
                          • 2012-11-28
                          • 1970-01-01
                          • 2010-11-03
                          相关资源
                          最近更新 更多