Как создать собственное представление с вложенным XML в качестве содержимого - PullRequest
0 голосов
/ 20 октября 2018

У меня проблема с созданием пользовательского компонента представления и последующим отображением вложенного содержимого xml, когда элемент управления определен в моих макетах.

Я пробовал перебирать дочерние элементы и получать только вложенные элементы, а затем использоватьremoveChild, затем addChild, чтобы поместить элементы управления во вложенный элемент управления, но это не работает.

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

Реализация компонента в моей деятельности. Xaml

<com.syntax.sonr.components.SonrCard
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:orientation="vertical"
                        ads:title="@string/description">

                        <TextView
                            android:id="@+id/description_text"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:layout_marginBottom="16dp"
                            android:layout_marginLeft="16dp"
                            android:layout_marginRight="16dp"
                            tools:text="Lorem ipsum dolor sit amet, consectetuer adipiscing elit. Donec odio. Quisque volutpat mattis eros. Nullam malesuada erat ut turpis. Suspendisse urna nibh, viverra non, semper suscipit, posuere a, pede." />

                    </com.syntax.sonr.components.SonrCard>

Файл merge.xml выглядит следующим образом

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


    <TextView
        android:id="@+id/title"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_marginBottom="8dp"
        android:layout_marginLeft="16dp"
        android:layout_marginRight="16dp"
        android:layout_marginTop="16dp"
        android:fontFamily="@font/open_sans_light"
        android:textSize="18sp"
        tools:text="Title" />

    // I would like to display the content (TextView) here


    <View
        android:id="@+id/border"
        android:layout_width="match_parent"
        android:layout_height="6dp"
        android:background="#c1c1c1" />

Я создал производный класс от RelativeLayout и могу получить атрибуты

public class SonrCard extends RelativeLayout {

String _title;
TextView _titleTextView;
LinearLayout _card;
FrameLayout _content;

public SonrCard(Context context) {
    super(context);
}

public SonrCard(Context context, @Nullable AttributeSet attrs) {
    super(context, attrs);

    getAttributes(context, attrs);
    initializeView(context);
}

public SonrCard(Context context, @Nullable AttributeSet attrs, int defStyleAttr) {
    super(context, attrs, defStyleAttr);

    getAttributes(context, attrs);
    initializeView(context);
}

public SonrCard(Context context, AttributeSet attrs, int defStyleAttr, int defStyleRes) {
    super(context, attrs, defStyleAttr, defStyleRes);

    getAttributes(context, attrs);
    initializeView(context);
}

private void initializeView(Context context) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
    inflater.inflate(R.layout.sonrcard_component_view, this);
}

private void getAttributes(Context context, AttributeSet attrs) {

    TypedArray attributes = context.obtainStyledAttributes(attrs, R.styleable.SonrCard);
    _title = attributes.getString(R.styleable.SonrCard_title);

    attributes.recycle();
}

@Override
protected void onFinishInflate() {
    super.onFinishInflate();

    _card = findViewById(R.id.sonr_card);
    _titleTextView = findViewById(R.id.title);
    _titleTextView.setText(_title);
    _content = findViewById(R.id.content);

    final int count = _card.getChildCount();

    for (int i = 0; i < count; i++) {
        final View child = _card.getChildAt(i);
        int id = child.getId();

        if (id != R.id.title && id != R.id.border){
            _card.removeView(child);
            _content.addView(child);
        }
    }
}

}

Спасибо

1 Ответ

0 голосов
/ 20 октября 2018

Вместо <Merge> почему бы вам не использовать <Include>?

Так что замените merge.xml на

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
   android:layout_width="fill_parent"
   android:layout_height="fill_parent"
   android:orientation="vertical" >


<TextView
    android:id="@+id/title"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:layout_marginBottom="8dp"
    android:layout_marginLeft="16dp"
    android:layout_marginRight="16dp"
    android:layout_marginTop="16dp"
    android:fontFamily="@font/open_sans_light"
    android:textSize="18sp"
    tools:text="Title" />

<include 
android:id="@+id/myIncludedLayout"
layout="@layout/yourSonrCardLayout"/>


<View
    android:id="@+id/border"
    android:layout_width="match_parent"
    android:layout_height="6dp"
    android:background="#c1c1c1" />

Подробнее о Повторное использование макетовс тегом Включить

Для раздувания Включенного макета

View includedLayout = findViewById(R.id.myIncludedLayout);

// geting the description_text TextView declared in yourSonrCardLayout.xml by myIncludedLayout
TextView description_text= (TextView) myIncludedLayout.findViewById(R.id.description_text);
description_text.setText("this is header text 3");
...