Как изменить атрибут Layout внутриполностью с Java? - PullRequest
0 голосов
/ 27 января 2019

У меня есть приложение калькулятора, которое имеет несколько тем.Я разработал несколько файлов макетов и пытаюсь изменить тег макета, если пользователь изменил тему в настройках.

Вот как отображается цифровая клавиатура, когда я вручную изменяю макет в xml.

enter image description here rect.xml

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent">
    <!-- all rectangular button codes -->
</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here циркуляр.xml

<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent">
    <!-- all rectangular button codes -->
</androidx.constraintlayout.widget.ConstraintLayout>

, а здесь - activity_main.xml

<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout 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:layout_height="match_parent"
    tools:context=".MainActivity">

    <TextView
        android:id="@+id/tvSource"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="center_vertical|start"
        android:hint="Enter a number"
        android:paddingStart="16dp"
        android:paddingEnd="16dp"
        android:textSize="16sp"
        app:layout_constraintBottom_toTopOf="@+id/tvTarget"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="parent"
        app:layout_constraintVertical_chainStyle="spread" />

    <TextView
        android:id="@+id/tvTarget"
        android:layout_width="0dp"
        android:layout_height="0dp"
        android:gravity="center_vertical|start"
        android:hint="Do some calculations to see the answer"
        android:paddingStart="16dp"
        android:paddingEnd="16dp"
        android:textSize="16sp"
        app:layout_constraintBottom_toTopOf="@+id/include"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintHorizontal_bias="0.5"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toBottomOf="@+id/tvSource" />

    <androidx.constraintlayout.widget.Guideline
        android:id="@+id/horizontalGuideline"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:orientation="horizontal"
        app:layout_constraintGuide_percent="0.25" />

    <include
        android:id="@+id/include"
        layout="@layout/basic_numpad_rectangular_flat_multi_color"
        android:layout_width="0dp"
        android:layout_height="0dp"
        app:layout_constraintBottom_toBottomOf="parent"
        app:layout_constraintEnd_toEndOf="parent"
        app:layout_constraintStart_toStartOf="parent"
        app:layout_constraintTop_toTopOf="@+id/horizontalGuideline" />

    <Button
        android:id="@+id/bSetting"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:layout_marginTop="8dp"
        android:layout_marginEnd="8dp"
        android:text="Setting"
        app:layout_constraintEnd_toEndOf="@+id/tvSource"
        app:layout_constraintTop_toTopOf="parent" />

</androidx.constraintlayout.widget.ConstraintLayout>

вот что я пытался изменить атрибут макета тега include с прямоугольного на круговой:

View circularComplete =  LayoutInflater.from(this).inflate(R.layout.basic_numpad_circular_complete, null);
ViewGroup viewGroup = findViewById(R.id.include);
viewGroup.removeAllViews();
viewGroup.addView(circularComplete);

он меняет макет, но не сохраняет ограничений или пробелов возле каждой кнопки.

enter image description here

Как программно изменить атрибут макета, чтобы он сохранял все ограничения и пробелы?

1 Ответ

0 голосов
/ 27 января 2019

Измените эту строку:

View circularComplete =  LayoutInflater.from(this).inflate(R.layout.basic_numpad_circular_complete, null);

на это вместо:

View circularComplete =  LayoutInflater.from(this).inflate(R.layout.basic_numpad_circular_complete, viewGroup, false);

Второй аргумент вызова inflate() - это родительское представление, используемоеинтерпретировать LayoutParams завышенного представления.Поскольку вы передаете null, LayoutParams завышенного представления (наиболее важно, layout_width и layout_height) игнорируются, и вместо них используются значения по умолчанию.Для ширины / высоты по умолчанию используется WRAP_CONTENT.

. Передав viewGroup в качестве родителя (и false в качестве третьего аргумента), LayoutParams вашего раздутого представления будет соблюдаться, и его размер будетустановлен правильно.

Вы также можете не вообще передавать третий аргумент и избегать необходимости делать вызов addView():

ViewGroup viewGroup = findViewById(R.id.include);
viewGroup.removeAllViews();
LayoutInflater.from(this).inflate(R.layout.basic_numpad_circular_complete, viewGroup);

против

ViewGroup viewGroup = findViewById(R.id.include);
viewGroup.removeAllViews();
View circularComplete =  LayoutInflater.from(this).inflate(R.layout.basic_numpad_circular_complete, viewGroup, false);
viewGroup.addView(circularComplete);
...