有 Java 编程相关的问题?

你可以在下面搜索框中键入要查询的问题!

安卓是否以编程方式更改视图的右边距?

这个属性可以在Java代码中动态更改吗

安卓:layout_marginRight

我有一个TextView,它必须动态地改变它在左边一些像素的位置

如何以编程方式进行


共 (4) 个答案

  1. # 1 楼答案

    更新:Android KTX

    Core KTX module为作为Android框架一部分的公共库提供扩展,其中^{}

    dependencies {
        implementation "androidx.core:core-ktx:{latest-version}"
    }
    

    以下扩展功能便于处理边距:

    Note: they are all extension functions of MarginLayoutParams, so first you need to get and cast the layoutParams of your view:

    val params = (myView.layoutParams as ViewGroup.MarginLayoutParams)
    
    • ^{}扩展函数:

    设置ViewGroupMarginLayoutParams中所有轴的边距。(必须以像素为单位提供尺寸,如果要使用dp,请参阅最后一节)

    inline fun MarginLayoutParams.setMargins(@Px size: Int): Unit
    // E.g. 16px margins
    params.setMargins(16)
    
    • ^{}扩展函数:

    更新ViewGroupViewGroup.MarginLayoutParams中的页边距

    inline fun MarginLayoutParams.updateMargins(
        @Px left: Int = leftMargin, 
        @Px top: Int = topMargin, 
        @Px right: Int = rightMargin, 
        @Px bottom: Int = bottomMargin
    ): Unit
    // Example: 8px left margin 
    params.updateMargins(left = 8)
    
    • ^{}扩展函数:

    更新ViewGroupMarginLayoutParams中的相对边距(开始/结束,而不是左/右)

    inline fun MarginLayoutParams.updateMarginsRelative(
        @Px start: Int = marginStart, 
        @Px top: Int = topMargin, 
        @Px end: Int = marginEnd, 
        @Px bottom: Int = bottomMargin
    ): Unit
    // E.g: 8px start margin 
    params.updateMargins(start = 8)
    

    以下扩展属性便于获取当前页边距:

    inline val View.marginBottom: Int
    inline val View.marginEnd: Int
    inline val View.marginLeft: Int
    inline val View.marginRight: Int
    inline val View.marginStart: Int
    inline val View.marginTop: Int
    // E.g: get margin bottom
    val bottomPx = myView1.marginBottom
    
    • 使用dp代替px

    如果要使用dp(与密度无关的像素)而不是px,则需要首先转换它们。使用以下扩展属性可以轻松完成此操作:

    val Int.px: Int
        get() = (this * Resources.getSystem().displayMetrics.density).toInt()
    

    然后可以调用前面的扩展函数,如:

    params.updateMargins(start = 16.px, end = 16.px, top = 8.px, bottom = 8.px)
    val bottomDp = myView1.marginBottom.dp
    

    旧答案:

    在Kotlin中,您可以声明如下扩展函数:

    fun View.setMargins(
        leftMarginDp: Int? = null,
        topMarginDp: Int? = null,
        rightMarginDp: Int? = null,
        bottomMarginDp: Int? = null
    ) {
        if (layoutParams is ViewGroup.MarginLayoutParams) {
            val params = layoutParams as ViewGroup.MarginLayoutParams
            leftMarginDp?.run { params.leftMargin = this.dpToPx(context) }
            topMarginDp?.run { params.topMargin = this.dpToPx(context) }
            rightMarginDp?.run { params.rightMargin = this.dpToPx(context) }
            bottomMarginDp?.run { params.bottomMargin = this.dpToPx(context) }
            requestLayout()
        }
    }
    
    fun Int.dpToPx(context: Context): Int {
        val metrics = context.resources.displayMetrics
        return TypedValue.applyDimension(TypedValue.COMPLEX_UNIT_DIP, this.toFloat(), metrics).toInt()
    }
    

    然后你可以这样称呼它:

    myView1.setMargins(8, 16, 34, 42)
    

    或:

    myView2.setMargins(topMarginDp = 8) 
    
  2. # 2 楼答案

    使用LayoutParams(如前所述)。但是,请小心选择哪个布局参数。根据https://stackoverflow.com/a/11971553/3184778“您需要使用与正在处理的视图的父视图相关的视图,而不是实际视图”

    例如,如果TextView位于TableRow内,则需要使用TableRow。LayoutParams而不是RelativeLayout或LinearLayout

  3. # 3 楼答案

    编辑:一种更通用的方法,不依赖于布局类型(除此之外,它是一种支持边距的布局类型):

    public static void setMargins (View v, int l, int t, int r, int b) {
        if (v.getLayoutParams() instanceof ViewGroup.MarginLayoutParams) {
            ViewGroup.MarginLayoutParams p = (ViewGroup.MarginLayoutParams) v.getLayoutParams();
            p.setMargins(l, t, r, b);
            v.requestLayout();
        }
    }
    

    您应该检查文档中的TextView。基本上,您需要获取TextView的LayoutParams对象,修改边距,然后将其设置回TextView。假设它处于线性布局,请尝试以下操作:

    TextView tv = (TextView)findViewById(R.id.my_text_view);
    LinearLayout.LayoutParams params = (LinearLayout.LayoutParams)tv.getLayoutParams();
    params.setMargins(0, 0, 10, 0); //substitute parameters for left, top, right, bottom
    tv.setLayoutParams(params);
    

    我现在无法测试它,所以我的演员阵容可能会有点偏离,但是需要修改LayoutParams来更改边距

    Don't forget that if your TextView is inside, for example, a RelativeLayout, one should use RelativeLayout.LayoutParams instead of LinearLayout.LayoutParams

  4. # 4 楼答案

    使用此功能设置所有类型的页边距

          public void setViewMargins(Context con, ViewGroup.LayoutParams params,      
           int left, int top , int right, int bottom, View view) {
    
        final float scale = con.getResources().getDisplayMetrics().density;
        // convert the DP into pixel
        int pixel_left = (int) (left * scale + 0.5f);
        int pixel_top = (int) (top * scale + 0.5f);
        int pixel_right = (int) (right * scale + 0.5f);
        int pixel_bottom = (int) (bottom * scale + 0.5f);
    
        ViewGroup.MarginLayoutParams s = (ViewGroup.MarginLayoutParams) params;
        s.setMargins(pixel_left, pixel_top, pixel_right, pixel_bottom);
    
        view.setLayoutParams(params);
    }