Как получить правильную высоту линейной компоновки программно?

#android #xml #android-layout #kotlin

#Android #xml #android-layout #kotlin

Вопрос:

Здесь я устанавливаю высоту корневого макета как android:layout_height=»400dp».

 <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:id="@ id/container"
android:orientation="vertical"
android:layout_height="400dp"
tools:context=".FirstFragment">


<ImageButton
    android:id="@ id/sleep_timer_btn"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:background="@drawable/ic_launcher_background"
    android:gravity="center_vertical|center_horizontal"
    android:padding="20dp"
    android:scaleType="fitXY"
    android:src="@drawable/ic_launcher_background"
    app:layout_constraintBottom_toBottomOf="@ id/guideline31"
    app:layout_constraintDimensionRatio="1:1"
    app:layout_constraintEnd_toEndOf="@ id/guideline24"
    app:layout_constraintStart_toStartOf="@ id/guideline23"
    app:layout_constraintTop_toTopOf="@ id/guideline30" />
<TextView
    android:id="@ id/textview_first"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/hello_first_fragment"
    app:layout_constraintBottom_toTopOf="@id/button_first"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toTopOf="parent" />


<Button
    android:id="@ id/button_first"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:text="@string/next"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_constraintEnd_toEndOf="parent"
    app:layout_constraintStart_toStartOf="parent"
    app:layout_constraintTop_toBottomOf="@id/textview_first" />
</LinearLayout>
  

В моем случае я хочу получить высоту контейнера программно (400dp). я пытаюсь всеми методами

 container.measure(View.MeasureSpec.UNSPECIFIED, View.MeasureSpec.UNSPECIFIED)
container.measure(View.MeasureSpec.AT_MOST, View.MeasureSpec.AT_MOST)
container.measure(View.MeasureSpec.EXACTLY, View.MeasureSpec.EXACTLY)
val height = measuredHeight
  

а также

     val viewTreeObserver: ViewTreeObserver = container.viewTreeObserver
    if (viewTreeObserver.isAlive) {
        viewTreeObserver.addOnGlobalLayoutListener(object :
            ViewTreeObserver.OnGlobalLayoutListener {
            override fun onGlobalLayout() {
                container.viewTreeObserver.removeOnGlobalLayoutListener(this)
                val viewHeight: Int = container.height
                val viewHeight1: Int = container.measuredHeight
            }
        })
     }
  

Ничего не работает.как получить высоту контейнера (400) программно?

Ответ №1:

прежде всего, вам нужен метод для преобразования px в dp :

 public float convertPixelsToDp(float px, Context context){
    return px / ((float) context.getResources().getDisplayMetrics().densityDpi / DisplayMetrics.DENSITY_DEFAULT);
}
  

затем вы можете получить высоту вашего LinearLayout вот так и показать это в тосте:

 final LinearLayout layout = findViewById(R.id.container);

    ViewTreeObserver vto = layout.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                layout.getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                layout.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }
            int width  = layout.getMeasuredWidth(); // this method return px value
            int height = layout.getMeasuredHeight(); // this method return px value

            Toast.makeText(MainActivity.this, "height is : "   convertPixelsToDp(height, MainActivity.this), Toast.LENGTH_LONG).show();
        }
    });