0

private LinearLayout subtitlePanel;

FrameLayout.LayoutParams layoutParams= (FrameLayout.LayoutParams) subtitlePanel.getLayoutParams();
    float dp=Utils.convertPixelsToDp(30f,context);
    if (bMargin) layoutParams.setMargins(0,0,0,0);
    else layoutParams.setMargins(0,0,0, (int) dp);
    subtitlePanel.setLayoutParams(layoutParams);

    <?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
             xmlns:tools="http://schemas.android.com/tools"
             android:orientation="vertical"
             android:background="@color/transparent"
             android:layout_width="match_parent"
             android:layout_height="match_parent">
    <LinearLayout
        android:layout_width="match_parent"
        android:layout_gravity="bottom"
        android:gravity="center_vertical"
        android:id="@+id/subtitlePanel"
        android:background="#66000000"
        android:layout_marginBottom="30dp"
        android:layout_height="wrap_content">
        <ImageButton
            android:layout_width="50dp"
            android:id="@+id/subtitleLeftButton"
            android:background="@color/transparent"
            android:src="@mipmap/arrow_prev_white"
            android:layout_height="50dp"/>
        <TextView
            android:layout_width="match_parent"
            tools:text="textsd"
            android:gravity="center"
            android:id="@+id/subtitleText"
            android:textSize="16sp"
            android:textColor="#fff"
            android:layout_weight="1"
            android:layout_height="wrap_content"/>
        <ImageButton
            android:layout_width="50dp"
            android:id="@+id/subtitleRightButton"
            android:background="@color/transparent"
            android:src="@mipmap/arrow_next_white"
            android:layout_height="50dp"/>
    </LinearLayout>
</FrameLayout>

 public static float convertPixelsToDp(float px, Context context){
    Resources resources = context.getResources();
    DisplayMetrics metrics = resources.getDisplayMetrics();
    float dp = px / ((float)metrics.densityDpi / DisplayMetrics.DENSITY_DEFAULT);
    return dp;
}

Я хочу программно изменить margin в subtitlePanel. Но в место того чтобы изменилось marginBottom на 30 dp. Он изменяется на 5 dp.

Тоесть наглядно видно чтобы на пару пиксель панель поднимается.

1 ответ 1

1

Секрет кроется в этих строчках:

float dp=Utils.convertPixelsToDp(30f,context);
...
layoutParams.setMargins(0,0,0, (int) dp);

Вы 30 пикселей конвертировали в dp, после чего передали dp в метод, принимающий пиксели.

Передавайте значения в пикселях напрямую без конвертации.

Ваш ответ

By clicking “Отправить ответ”, you agree to our terms of service and acknowledge you have read our privacy policy.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.