Два RecyclerView внутри одного Scrollview, один не показывает содержимое - PullRequest
0 голосов
/ 06 ноября 2019

У меня проблема с двумя RecyclerView внутри одного и того же ScrollView (я тоже пробовал то же самое с NestestScrollView). Внутри ScrollView у меня есть также некоторые другие View объекты, которые образуют своего рода «секцию заголовка» фрагмента. Затем я хотел бы показать горизонтальный список RecyclerView и, наконец, над горизонтальным списком вертикальный список других RecyclerView. Однако правильно отображается только горизонтальный. Несмотря на то, что Adapter вертикального правильно инициализируется с некоторыми объектами, при запуске приложения вертикальный список пуст. Я думаю, что это проблема, связанная с моим макетом.

Это мой .xml файл:

<?xml version="1.0" encoding="utf-8"?>
<ScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/profile_coordinator"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="20dp">

            <!-- Here I have some other views (ImageView, TextView, etc.) -->


        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="10dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/active_promos"
                android:textStyle="bold"
                android:textColor="@color/colorPrimary"
                android:textSize="18sp"
                android:layout_marginBottom="10sp"/>

            <!-- Horizontal List of RecyclerView -->
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/promo_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:orientation="horizontal"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                android:layout_marginBottom="20sp"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/news"
                android:textStyle="bold"
                android:textColor="@color/colorPrimary"
                android:textSize="18sp"
                android:layout_marginBottom="10sp"/>

            <!-- Vertical List of RecyclerView -->
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/news_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="match_parent" />
        </LinearLayout>

    </LinearLayout>

</ScrollView>

Поскольку объекты для отображения одинаковы (но семантика другая),Я использую тот же класс Adapter, который загружает два разных макета xml в соответствии с типом отображаемого объекта.

Это Adapter.java:

public class NewsAdapter extends RecyclerView.Adapter {

private List<NewsPromotion> newsPromotions;
private boolean promos;

public NewsAdapter(List<NewsPromotion> newsPromotions, boolean promos) {
    this.newsPromotions = newsPromotions;
    this.promos = promos;
}

public void setData(List<NewsPromotion> newsPromotions){
    this.newsPromotions = newsPromotions;
}

@NonNull
@Override
public RecyclerView.ViewHolder onCreateViewHolder(@NonNull ViewGroup parent, int viewType) {

    RecyclerView.ViewHolder viewHolder;

    if(promos) {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.promo_recyclerview_item,
                parent, false);

        viewHolder = new PromoViewHolder(mView);

    }else {
        View mView = LayoutInflater.from(parent.getContext()).inflate(R.layout.recyclerview_item_row,
                parent, false);

        viewHolder = new NewsViewHolder(mView);
    }

    return viewHolder;
}

@Override
public void onBindViewHolder(@NonNull RecyclerView.ViewHolder holder, int position) {

    Log.d("Adapter", newsPromotions.get(position).title);

    if(promos){
        PromoViewHolder viewHolder = (PromoViewHolder) holder;
        Picasso.get().load(RestClient.BASE_IMAGE_URL + newsPromotions.get(position).image).into(viewHolder.mImage);
    }else {


        NewsViewHolder viewHolder = (NewsViewHolder) holder;

        Picasso.get().load(RestClient.BASE_IMAGE_URL + newsPromotions.get(position).image).into(viewHolder.mImage);
        viewHolder.mTitle.setText(newsPromotions.get(position).title);
        viewHolder.mDescription.setText(newsPromotions.get(position).content);
    }
}

@Override
public int getItemCount() {
    return newsPromotions.size();
}

public class NewsViewHolder extends RecyclerView.ViewHolder {

    ImageView mImage;
    TextView mTitle;
    TextView mDescription;

    private NewsViewHolder(View itemView) {
        super(itemView);

        mImage = itemView.findViewById(R.id.ivImage);
        mTitle = itemView.findViewById(R.id.tvTitle);
        mDescription = itemView.findViewById(R.id.tvDescription);
    }
}

public class PromoViewHolder extends RecyclerView.ViewHolder {

    ImageView mImage;

    private PromoViewHolder(View itemView) {
        super(itemView);

        mImage = itemView.findViewById(R.id.ivImage);
    }
}

}

И вот как я инициализирую два адаптера во фрагменте:

RecyclerView promoRecycleView = activity.findViewById(R.id.promo_recyclerview);
promoAdapter = new NewsAdapter(new ArrayList<NewsPromotion>(), true);
promoRecycleView.setAdapter(promoAdapter);

RecyclerView newsRecycleView = activity.findViewById(R.id.news_recyclerview);
newsAdapter = new NewsAdapter(new ArrayList<NewsPromotion>(), false);
newsRecycleView.setAdapter(newsAdapter);

Наконец, вот как я отправляю объект адаптерам:

promoAdapter.setData(promos);
promoAdapter.notifyDataSetChanged();

newsAdapter.setData(news);
newsAdapter.notifyDataSetChanged();

Ответы [ 3 ]

0 голосов
/ 06 ноября 2019

Пожалуйста, опубликуйте свой адаптер и item_layout. Потому что ваш заданный макет работает идеально для меня.

0 голосов
/ 06 ноября 2019

enter image description here

Нет проблем с вашим макетом, я запустил в myAppliaction, некоторые проблемы с адаптером, пожалуйста, опубликуйте / вставьте вашу активность и код адаптера.

0 голосов
/ 06 ноября 2019

Если вы посмотрите документацию на RecyclerView, вы увидите, что вам нужно указать размер списка. Для RecyclerView нет содержимого для переноса, потому что это dymanic виджет. Так что вам нужно будет настроить свою реализацию на что-то вроде следующего.

<?xml version="1.0" encoding="utf-8"?>
<NestedScrollView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:id="@+id/profile_coordinator"
    xmlns:app="http://schemas.android.com/apk/res-auto"
    tools:context=".HomeFragment">

    <LinearLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:orientation="vertical">

        <RelativeLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:paddingBottom="20dp">

            <!-- Here I have some other views (ImageView, TextView, etc.) -->


        </RelativeLayout>

        <LinearLayout
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:orientation="vertical"
            android:padding="10dp">

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/active_promos"
                android:textStyle="bold"
                android:textColor="@color/colorPrimary"
                android:textSize="18sp"
                android:layout_marginBottom="10sp"/>

            <!-- Horizontal List of RecyclerView -->
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/promo_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="200dp"
                android:orientation="horizontal"
                app:layoutManager="androidx.recyclerview.widget.LinearLayoutManager"
                android:layout_marginBottom="20sp"/>

            <TextView
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:text="@string/news"
                android:textStyle="bold"
                android:textColor="@color/colorPrimary"
                android:textSize="18sp"
                android:layout_marginBottom="10sp"/>

            <!-- Vertical List of RecyclerView -->
            <androidx.recyclerview.widget.RecyclerView
                android:id="@+id/news_recyclerview"
                android:layout_width="match_parent"
                android:layout_height="500dp" />
        </LinearLayout>

    </LinearLayout>

</ScrollView>
...