Динамическое добавление относительного макета в линейный макет - PullRequest
6 голосов
/ 09 мая 2019

У меня есть LinearLayout внутри DrawerLayout с именем "контейнер".Во время выполнения я пытаюсь добавить RelativeLayout внутри «контейнера».Это приводит к тому, что RelativeLayout выравнивание не работает должным образом, т.е. прогресс идет по изображению логотипа.

Относительный макет:

<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="@drawable/bg"
    android:keepScreenOn="true">
    <ImageView
        android:id="@+id/logo"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_centerHorizontal="true"
        android:layout_centerVertical="true"
        android:src="@drawable/logo" />

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_below="@+id/logo"
        android:layout_centerHorizontal="true"
        android:layout_marginTop="20dp"
        android:gravity="center"
        android:orientation="vertical"
        android:paddingStart="8dp"
        android:paddingEnd="5dp">


        <ProgressBar
            android:id="@+id/progressBar"
            style="?android:attr/progressBarStyle"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginStart="1dp"
            android:visibility="gone" />

        <TextView
            android:id="@+id/tv_network_error"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="false"
            android:gravity="center"
            android:text="@string/no_network"
            android:textColor="#E10000"
            android:textSize="30sp"
            android:visibility="visible" />

    </LinearLayout>

    <TextView
        android:id="@+id/tv_software_version"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_alignParentEnd="true"
        android:layout_alignParentBottom="true"
        android:layout_gravity="center_horizontal"
        android:gravity="center_horizontal"
        android:paddingRight="20dp"
        android:paddingBottom="20dp"
        android:text="Version"
        android:textColor="@android:color/darker_gray" />
</RelativeLayout>

DrawerLayout с контейнером

<?xml version="1.0" encoding="utf-8"?>
<android.support.v4.widget.DrawerLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    android:id="@+id/drawer_layout"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:fitsSystemWindows="false">
    <LinearLayout
        android:id="@+id/contentPanel"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:orientation="vertical">
    </LinearLayout>

    <android.support.design.widget.NavigationView
        android:id="@+id/nav_view"
        android:layout_width="wrap_content"
        android:layout_height="match_parent"
        android:layout_gravity="end"
        android:background="@color/white"
        android:fitsSystemWindows="false"
        app:menu="@menu/activity_main_drawer" />
</android.support.v4.widget.DrawerLayout>

Внедрение макета во время выполнения

protected View getRootView(View view) {
        View sliderLayout = LayoutInflater.from(this).inflate(R.layout.slider_layout, null);
        LinearLayout layout = (LinearLayout) sliderLayout.findViewById(R.id.contentPanel);
        layout.addView(view);
        return sliderLayout;
    }

Ответы [ 2 ]

3 голосов
/ 21 мая 2019

Я не уверен, где getRootView() находится в вашем коде. Если уточнить, я могу предоставить лучшее решение.

Однако я создал проект с активностью навигационного ящика, определил RelativeLayout для динамического добавления в layout_to_be_added.xml и провел следующий эксперимент в onCreate() MainActivity:

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

    ...

    final LinearLayout contentPanel = findViewById(R.id.contentPanel);
    contentPanel.post(new Runnable() {
        @Override
        public void run() {
            View layoutToBeAdded = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_to_be_added, null);
            contentPanel.addView(layoutToBeAdded);
            // contentPanel.invalidate();
        }
    });
}

Это привело к проблеме, о которой вы упомянули, индикатор выполнения и текст не ниже центрированного логотипа, как показано здесь:

Probably the layout params are not correct....

Кажется, нулевой корень вызывает неправильные вычисления или оценки, поэтому я обновил строку inflate() следующим образом:

View layoutToBeAdded = LayoutInflater.from(MainActivity.this).inflate(R.layout.layout_to_be_added, contentPanel, false);

Здесь мы предоставляем контейнер как root, но мы не прикрепляем к нему макет слайдера. Таким образом, корень используется только для вычисления правильных LayoutParams, и мы получаем ожидаемый результат, как показано ниже:

Correct result

0 голосов
/ 23 мая 2019

Я изменился ниже черты

contentPanel.addView(view);

до

contentPanel.addView(view,LinearLayout.LayoutParams.MATCH_PARENT,LinearLayout.LayoutParams.MATCH_PARENT);

Это сработало для меня.

...