如何在 Android 中将 UI 元素翻译其高度的 %50%?



我想将垂直轴上的相对布局平移其高度的 %50%。怎么办?

<RelativeLayout
android:id="@+id/rl"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:translationY="50dp"> <!-- i tried 50% , .50. But it does not work.

然后我尝试在活动的onCreate中找到它的高度,然后动态翻译%50百分比。 但高度返回零。

onCreate(){
...
RelativeLayout rl = findViewById(R.id.RL);
rl.getHeight();
}

怎么办?

您无法在 onCreate(( 中检索视图的高度。因为它还没有被测量和绘制。试试这个:

RelativeLayout rl = findViewById(R.id.RL);
rl.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
public void onGlobalLayout() {
rl.getMeasuredHeight();
}
});

获得高度后,您可以根据需要使用它进行翻译。

Android有一些烦人的错误,使我们使用无用的黑客。为了在onCreate中获取高度,我使用了这个:

var handler=Handler()
handler.postDelayed(object:Runnable{
override fun run() {
findViewById<RelativeLayout>(R.id.toMove).y=findViewById<RelativeLayout>(R.id.toMove).y+(findViewById<RelativeLayout>(R.id.toMove).height/2)
}
}, 200)

我知道这是 200 个工厂的延迟,t 不是最好的解决方案,但它很容易实施并且工作正常。

最新更新