Android 以编程方式获取像素百分比大小

Android 以编程方式获取像素百分比大小,android,android-layout,kotlin,android-view,android-constraintlayout,Android,Android Layout,Kotlin,Android View,Android Constraintlayout,我有一份指南,在页面左侧打八五折 我可以在这个代码中得到它的百分比: float percent = ((ConstraintLayout.LayoutParams) guideline.getLayoutParams()).guidePercent; 产出:0.15 如何获取像素值或dpi值?我找不到任何直接转换成dp公式的百分比,因为手机的dp在多个屏幕上是不同的。但我有简单的逻辑来获取dp中的值 1) 计算屏幕宽度(500dp) 2) 计算版面宽度的边距百分比(15%) float d

我有一份
指南
,在页面左侧打八五折

我可以在这个代码中得到它的百分比:

float percent = ((ConstraintLayout.LayoutParams) guideline.getLayoutParams()).guidePercent;
产出:0.15


如何获取像素值或dpi值?

我找不到任何直接转换成dp公式的百分比,因为手机的dp在多个屏幕上是不同的。但我有简单的逻辑来获取dp中的值

1) 计算屏幕宽度(500dp)

2) 计算版面宽度的边距百分比(15%)

float  dpvalue=totalwidth * percentage 

//500 *(0.15) =75(dpvalue)

此逻辑将适用于所有设备大小。

假设已布置了
ConstraintLayout
,则可以使用
guideline.getTop()
获得顶部或左侧的像素距离,对于水平方向,使用
guideline.getLeft()
获得垂直方向

如果
ConstraintLayout
尚未布局(假设您处于活动的
onCreate()
),则必须等待布局完成:


    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraint);
        constraintLayout.post(new Runnable() {
            @Override
            public void run() {
                Guideline guideline = findViewById(R.id.guideline);
                Log.i(TAG, guideline.getLeft() + "");
            }
        });
    }
注意,/将返回像素大小。此大小将指出
指南
与其父级之间的距离-
约束列表
。这意味着该值不是绝对值,而是相对于其父项的

如果您想获得一个绝对值(假设您的
ConstraintLayout
深入嵌套在视图层次结构中,并且您想了解
指南
距离屏幕左侧有多远),那么您必须利用API:

Java代码:

Guideline=(Guideline)findviewbyd(R.id.Guideline)
浮动百分比=((ConstraintLayout.LayoutParams)guideline.getLayoutParams()).guidePercent
科特林代码:

val-guideline1=findviewbyd(R.id.guideline)
val percent=(guideline1.layoutParams作为ConstraintLayout.layoutParams)。guidePercent

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        ConstraintLayout constraintLayout = (ConstraintLayout) findViewById(R.id.constraint);
        constraintLayout.post(new Runnable() {
            @Override
            public void run() {
                Guideline guideline = findViewById(R.id.guideline);
                int[] location = new int[2];
                guideline.getLocationOnScreen(location);
                Log.i(TAG, location[0] + " " + location[1]);
            }
        });
    }
val guideline1 = findViewById<Guideline>(R.id.guideline)
val percent = (guideline1.layoutParams as ConstraintLayout.LayoutParams).guidePercent