Как просто создать пользовательский вид без дублирования LinearLayout? - PullRequest
1 голос
/ 17 января 2020

Самый простой способ, который я нашел для создания собственного представления, так что мне не нужно обрабатывать раздражающие вещи, такие как переопределение метода onLayout (), - это заставить его наследовать от LinearLayout. У меня также есть LinearLayout в root связанного XML файла, который я раздуваю, поэтому есть 2 из них в root.

Как я могу оптимизировать это, удалив одно из этого дополнительный LinearLayout, но упрощать создание пользовательских представлений?

MyToolbar.kt:

class MyToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    LinearLayoutCompat(context, attrs, defStyleAttr) {

    private val binding = MyToolbarBinding.inflate(LayoutInflater.from(context), this, true)

    init {
         // [...] Initialization of my view ...
    }
}

my_toolbar. xml:

<LinearLayout
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <!-- Actual content of my view -->

</LinearLayout>

Ответы [ 2 ]

0 голосов
/ 17 января 2020

Что у меня есть сейчас после предложения @Pawel и @Cata. Это не работает, LinearLayout использует всю высоту родительского элемента, но он должен только переносить его содержимое.

MyToolbar.kt:

class MyToolbar @JvmOverloads constructor(
    context: Context,
    attrs: AttributeSet? = null,
    defStyleAttr: Int = 0
) :
    LinearLayoutCompat(context, attrs, defStyleAttr) {

    private val binding

    init {
        // Tried to add the attributes here as they seems ignored on the `merge` tag
        gravity = Gravity.CENTER_VERTICAL
        orientation = HORIZONTAL
        layoutParams = LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)

        binding = MyToolbarBinding.inflate(LayoutInflater.from(context), this)

        // [...] Initialization of the view ...
    }
}

my_toolbar. xml:

<merge
    xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:gravity="center_vertical"
    android:orientation="horizontal">

    <!-- Actual content of the view -->

</merge>
0 голосов
/ 17 января 2020

Как предположил Павел, вы можете использовать merge для этого.

Это пример с сайта разработчика:

<merge xmlns:android="http://schemas.android.com/apk/res/android">

    <!-- Here you can add your custom content views.. -->
    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/add"/>

    <Button
        android:layout_width="fill_parent"
        android:layout_height="wrap_content"
        android:text="@string/delete"/>

</merge>
...