Подтвердить что ты не робот

Макет, такой как приложение HotStar

Мне нужно создать макет, например HotStar App, но я немного запутался в том, что было бы best way для этого:

введите описание изображения здесь

  • Нужно ли мне несколько RecyclerView или достаточно одного RecyclerView?

  • Нужно ли мне вызывать несколько JSON или один JSON достаточно для извлечения данные с сервера?

  • Как использовать разные - разные макеты для вас могут также нравиться и Следить за клипами

4b9b3361

Ответ 1

С этим вы сможете создать тот же Look-And-Feel

1.- Для вкладки верхнего меню вам нужно выполнить макет TABS

2.- Для подробного раздела добавьте CARDS

3.- Разделитель для ваших разделов, используйте SUBHEADERS

Теперь, касаясь ваших вопросов:

1. Вы можете обрабатывать все только одним единственным RecyclerViews

2. Лучший подход - это получить отдельный JSON для каждого раздела, так как вы никогда не знаете, насколько большой будет каждый раздел. Это поможет значительно улучшить производительность и чистый код.

**

NEW UPDATE

**

Основная деятельность макета

<?xml version="1.0" encoding="utf-8"?>
    <RelativeLayout
        xmlns:app="http://schemas.android.com/apk/res-auto"
        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"
        tools:context="com.alphasystech.hotvideos.MainActivity">

        <android.support.design.widget.AppBarLayout
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

            <include
                android:layout_height="wrap_content"
                android:layout_width="match_parent"
                layout="@layout/toolbar_layout">

            </include>

            <android.support.design.widget.TabLayout
                android:layout_width="match_parent"
                android:layout_height="wrap_content"
                android:id="@+id/tabLayout"
                app:tabMode="fixed"
                app:tabGravity="fill"
                app:tabTextAppearance="@style/MyTabStyle">
            </android.support.design.widget.TabLayout>

        </android.support.design.widget.AppBarLayout>

        <android.support.v4.view.ViewPager
            android:layout_width="match_parent"
            android:layout_height="match_parent"
            android:id="@+id/viewPager">

        </android.support.v4.view.ViewPager>

    </RelativeLayout>

Макет вашего домашнего фрагмента (также вы можете клонировать его для MOVIES, SPORTS...)

<FrameLayout 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"
tools:context=".HomeFragment">

<!-- A RecyclerView with some commonly used attributes -->
<android.support.v7.widget.RecyclerView
    android:id="@+id/home_recyclerview"
    android:scrollbars="vertical"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"/>

Схема ваших карт для вашего домашнего фрагмента (также вы можете клонировать это для MOVIES, SPORTS...)

<?xml version="1.0" encoding="utf-8"?>
<android.support.v7.widget.CardView
    xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="wrap_content"
    android:id="@+id/card_view"
    android:layout_margin="5dp"
    card_view:cardBackgroundColor="#81C784"
    card_view:cardCornerRadius="12dp"
    card_view:cardElevation="3dp"
    card_view:contentPadding="4dp" >

    <RelativeLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:padding="16dp" >

        <ImageView
            android:layout_width="100dp"
            android:layout_height="100dp"
            android:id="@+id/item_image"
            android:layout_alignParentLeft="true"
            android:layout_alignParentTop="true"
            android:layout_marginRight="16dp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/item_title"
            android:layout_toRightOf="@+id/item_image"
            android:layout_alignParentTop="true"
            android:textSize="30sp"
            />

        <TextView
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:id="@+id/item_detail"
            android:layout_toRightOf="@+id/item_image"
            android:layout_below="@+id/item_title"
            />

    </RelativeLayout>
</android.support.v7.widget.CardView>

Скриншот:

образец скриншота

Я думаю, приведенный выше пример даст вам хорошее направление:)

Ответ 2

  • Нужно ли мне несколько RecyclerView или достаточно одного RecyclerView?

Одиночный RecyclerView достаточно.

  1. Нужно ли мне вызывать несколько JSON или одного JSON для получения данных с сервера?

Одиночный JSON ответ достаточно.

  1. Как использовать разные - разные макеты для вас могут также нравиться и должны следить за клипами.

Сделайте эту часть пользовательского интерфейса как строку RecyclerView.

строка RecyclerView

Это самое простое решение, если вы знаете максимальное количество элементов в строке. Ваша модель должна иметь данные каждой строки.

Пример компоновки строк:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:card_view="http://schemas.android.com/apk/res-auto"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:background="#ddd"
    android:orientation="vertical">

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


        <TextView
            android:id="@+id/textView"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginLeft="16dp"
            android:text="You May Also Like"
            android:textAppearance="?android:attr/textAppearanceLarge"
            android:textStyle="bold" />

        <View
            android:layout_width="0dp"
            android:layout_height="0dp"
            android:layout_weight="1" />

        <Button
            android:id="@+id/button"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_marginRight="16dp"
            android:text="MORE" />
    </LinearLayout>


    <TableLayout
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:layout_gravity="center_horizontal">


        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:id="@+id/item1_CV"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="4dp"
                android:layout_marginTop="8dp"
                android:layout_weight="1"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentStart="true"
                        android:layout_below="@+id/item1_image"
                        android:background="#fff"
                        android:orientation="vertical"
                        android:padding="8dp">

                        <TextView
                            android:id="@+id/item1_title"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Mere Rang Mein"
                            android:textColor="#000"
                            android:textSize="16sp" />

                        <TextView
                            android:id="@+id/item1_subTitle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:singleLine="true"
                            android:text="Romance, Hindi, Life OK"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textSize="12sp" />
                    </LinearLayout>

                    <ImageView
                        android:id="@+id/item1_image"
                        android:layout_width="match_parent"
                        android:layout_height="80dp"
                        android:background="#FF78aa" />
                </RelativeLayout>
            </android.support.v7.widget.CardView>


            <android.support.v7.widget.CardView
                android:id="@+id/item2_CV"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="4dp"
                android:layout_marginLeft="4dp"
                android:layout_marginRight="8dp"
                android:layout_marginTop="8dp"
                android:layout_weight="1"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentStart="true"
                        android:layout_below="@+id/item2_image"
                        android:background="#fff"
                        android:orientation="vertical"
                        android:padding="8dp">

                        <TextView
                            android:id="@+id/item2_title"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Mere Rang Mein"
                            android:textColor="#000"
                            android:textSize="16sp" />

                        <TextView
                            android:id="@+id/item2_subTitle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:singleLine="true"
                            android:text="Romance, Hindi, Life OK"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textSize="12sp" />
                    </LinearLayout>

                    <ImageView
                        android:id="@+id/item2_image"
                        android:layout_width="match_parent"
                        android:layout_height="80dp"
                        android:background="#FF78aa" />
                </RelativeLayout>
            </android.support.v7.widget.CardView>

        </TableRow>

        <TableRow
            android:layout_width="match_parent"
            android:layout_height="wrap_content">

            <android.support.v7.widget.CardView
                android:id="@+id/item3_CV"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="8dp"
                android:layout_marginRight="4dp"
                android:layout_marginTop="4dp"
                android:layout_weight="1"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentStart="true"
                        android:layout_below="@+id/item3_image"
                        android:background="#fff"
                        android:orientation="vertical"
                        android:padding="8dp">

                        <TextView
                            android:id="@+id/item3_title"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Mere Rang Mein"
                            android:textColor="#000"
                            android:textSize="16sp" />

                        <TextView
                            android:id="@+id/item3_subTitle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:singleLine="true"
                            android:text="Romance, Hindi, Life OK"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textSize="12sp" />
                    </LinearLayout>

                    <ImageView
                        android:id="@+id/item3_image"
                        android:layout_width="match_parent"
                        android:layout_height="80dp"
                        android:background="#FF78aa" />
                </RelativeLayout>
            </android.support.v7.widget.CardView>


            <android.support.v7.widget.CardView
                android:id="@+id/item4_CV"
                android:layout_width="0dp"
                android:layout_height="wrap_content"
                android:layout_marginBottom="8dp"
                android:layout_marginLeft="4dp"
                android:layout_marginRight="8dp"
                android:layout_marginTop="4dp"
                android:layout_weight="1"
                card_view:cardCornerRadius="4dp">

                <RelativeLayout
                    android:layout_width="match_parent"
                    android:layout_height="wrap_content">

                    <LinearLayout
                        android:layout_width="match_parent"
                        android:layout_height="wrap_content"
                        android:layout_alignParentEnd="true"
                        android:layout_alignParentLeft="true"
                        android:layout_alignParentRight="true"
                        android:layout_alignParentStart="true"
                        android:layout_below="@+id/item4_image"
                        android:background="#fff"
                        android:orientation="vertical"
                        android:padding="8dp">

                        <TextView
                            android:id="@+id/item4_title"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:text="Mere Rang Mein"
                            android:textColor="#000"
                            android:textSize="16sp" />

                        <TextView
                            android:id="@+id/item4_subTitle"
                            android:layout_width="wrap_content"
                            android:layout_height="wrap_content"
                            android:singleLine="true"
                            android:text="Romance, Hindi, Life OK"
                            android:textAppearance="?android:attr/textAppearanceSmall"
                            android:textSize="12sp" />
                    </LinearLayout>

                    <ImageView
                        android:id="@+id/item4_image"
                        android:layout_width="match_parent"
                        android:layout_height="80dp"
                        android:background="#FF78aa" />
                </RelativeLayout>
            </android.support.v7.widget.CardView>

        </TableRow>
    </TableLayout>
</LinearLayout>

Результат: Результат макета строки

Ответ 3

  • Нужно ли мне несколько RecyclerView или достаточно одного RecyclerView?

Для этой цели достаточно одного повторного просмотра с GridLayoutManager.

  1. Нужно ли мне вызывать несколько JSON или одного JSON для получения данных с сервера?

Единый ответ JSON будет выполнять вашу работу.

Ответ 4

Вы можете выполнить это, просто выставив сначала ТАБС и показывая свои КАРТЫ внутри ViewPager.

Что-то вроде этого....

@Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);
        toolbar = (Toolbar)findViewById(R.id.toolBar);
        setSupportActionBar(toolbar);
        tabLayout = (TabLayout)findViewById(R.id.tabLayout);
        viewPager = (ViewPager)findViewById(R.id.viewPager);

        viewPagerAdapter = new ViewPagerAdapter(getSupportFragmentManager());
        viewPagerAdapter.addFragments...

Ответ 5

    Do I need multiple RecyclerViews or single RecyclerView is enough?

одиночный RecyclerView.

    Do I need to call multiple JSONs or single JSON is enough to fetch data from server?

отдельные данные JSON с сервера будут выполнять вашу работу.

    How Do I use different - different layouts for You May Also Like and Must Watch Clips

использовать recyclerview с несколькими типами просмотра

public class MyAdapter extends RecyclerView.Adapter<RecyclerView.ViewHolder> {
    class ViewHolder0 extends RecyclerView.ViewHolder {
        ...
    }

    class ViewHolder2 extends RecyclerView.ViewHolder {
        ...
    }

    @Override
    public int getItemViewType(int position) {
        // Just as an example, return 0 or 2 depending on position
        // Note that unlike in ListView adapters, types don't have to be contiguous
        return position % 2 * 2;
    }

    @Override
    public RecyclerView.ViewHolder onCreateViewHolder(ViewGroup parent, int viewType) {
         switch (viewType) {
             case 0: return new ViewHolder0(...);
             case 2: return new ViewHolder2(...);
             ...
         }
    }
}

Использовать RecyclerView с заголовком и обычным типом элемента

Ответ 6

Используйте это как макет

<?xml version="1.0" encoding="utf-8"?>
<android.support.design.widget.CoordinatorLayout
    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:id="@+id/coordinator"
    android:layout_width="match_parent"
    android:layout_height="match_parent">

    <android.support.design.widget.AppBarLayout
        android:id="@+id/appbar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:tag="iv"
        android:theme="@style/ThemeOverlay.AppCompat.Dark.ActionBar">

        <android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="@color/primary"
            android:theme="@style/ToolbarStyle"
            android:gravity="center_vertical"
            app:popupTheme="@style/ThemeOverlay.AppCompat.Light"
            app:layout_scrollFlags="scroll|enterAlways|snap"
            style="@style/bold" />

        <android.support.design.widget.TabLayout
            android:id="@+id/tabs"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:theme="@style/TabLayoutStyle"
            android:animateLayoutChanges="true"
            app:tabMode="scrollable"
            app:tabTextAppearance="@style/TabStyle"/>

    </android.support.design.widget.AppBarLayout>

    <android.support.v4.view.ViewPager
        android:id="@+id/main_container"
        android:layout_width="match_parent"
        android:layout_height="match_parent"
        android:layout_gravity="fill_vertical"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

</android.support.design.widget.CoordinatorLayout>
  • CoordinatorLayout + AppBarLayout заставит панель инструментов прокручиваться по мере прокрутки макета

  • Создайте фрагмент для страниц в ViewPager и напишите FragmentStatePagerAdapter для него

  • Не забудьте вызвать tabLayout.setupWithViewPager(viewPager), чтобы надуть TabLayout

  • См. this для примера проекта

  • Внутри фрагмента используйте RecyclerView с GridLayoutManager и spanCount 2

  • Внутри реализации RecyclerView.Adapter используйте getItemViewType, чтобы указать количество типов типов, которые вы хотите. На скриншоте похоже, что у вас есть только 2 типа (или 3, если вы хотите, чтобы фрагмент видео был отдельным видомным видом. Обратите внимание, что вы все равно можете использовать один и тот же макет для разных типов виджетов, просто скройте/покажите просмотры, которые вы хотите в каждом представлении Это уменьшит дублирование макета). Прочитайте это, чтобы узнать, как его создать.

  • Используйте CardView, чтобы сделать карту изображения

  • Используйте Picasso, Glide, или Fresco для загрузки изображений внутри этих Карт (Picasso и Glide проще в использовании по сравнению с Fresco, но фреска лучше с памятью)

Нужно ли мне вызывать несколько JSON или одного JSON для получения данных с сервера?

Это полностью зависит от вас, вы можете идти в любом случае, однако получение всех данных в одном запросе сделает выборку быстрее.

PS: вы можете использовать GSON для разбора вашего Json и сохранить себя немного разумно.

Ответ 7

Нужно ли мне несколько RecyclerView или достаточно одного RecyclerView?

Достаточно одного.

Нужно ли мне называть несколько JSON или один JSON достаточно для извлечения данные с сервера?

Достаточно одного JSON.

Как использовать разные - разные макеты для вас могут также нравиться и Следить за клипами

  • 1 отдельный макет для заголовков разделов, поскольку они выглядят одинаково
  • 1 макет для элементов "You May Like Like"
  • 1 макет для пунктов "Обязательно следить за клипами", потому что они разные: у них есть метка "минут" и кнопка "играть". Вы можете использовать один и тот же макет и скрыть эти представления, когда это не нужно, это зависит от вас.

В библиотеке SectionedRecyclerViewAdapter вы можете добавить в свой RecyclerView разные "разделы", каждый раздел может иметь свой собственный заголовок, например, на изображение ниже:

Секция сетки с заголовком

Вам нужно создать классы "section":

class MustWatchClipsSection extends StatelessSection {

    String title;
    List<Clip> clipList;

    public MustWatchClipsSection(String title, List<Clip> clipList) {
        // call constructor with layout resources for this Section header, footer and items 
        super(R.layout.section_header, R.layout.section_footer,  R.layout.section_item);

        this.title = title;
        this.clipList = clipList;
    }

    @Override
    public int getContentItemsTotal() {
        return clipList.size(); // number of items of this section
    }

    @Override
    public RecyclerView.ViewHolder getItemViewHolder(View view) {
        // return a custom instance of ViewHolder for the items of this section
        return new MyItemViewHolder(view);
    }

    @Override
    public void onBindItemViewHolder(RecyclerView.ViewHolder holder, int position) {
        MyItemViewHolder itemHolder = (MyItemViewHolder) holder;

        // bind your view here
        itemHolder.tvItem.setText(clipList.get(position).getName());
    }

    @Override
    public RecyclerView.ViewHolder getHeaderViewHolder(View view) {
        return new SimpleHeaderViewHolder(view);
    }

    @Override
    public void onBindHeaderViewHolder(RecyclerView.ViewHolder holder) {
        MyHeaderViewHolder headerHolder = (MyHeaderViewHolder) holder;

        // bind your header view here
        headerHolder.tvItem.setText(date);
    }
}

Затем вы настроите RecyclerView своими разделами:

// Create an instance of SectionedRecyclerViewAdapter 
SectionedRecyclerViewAdapter sectionAdapter = new SectionedRecyclerViewAdapter();

MayAlsoLikeSection mySection1 = new MayAlsoLikeSection("You May Also Like", mediaList);
MustWatchClipsSection mySection2 = new MustWatchClipsSection("Must Watch Clips", clipList);

// Add your Sections
sectionAdapter.addSection(mySection1);
sectionAdapter.addSection(mySection2);

// Set up your RecyclerView with the SectionedRecyclerViewAdapter
RecyclerView recyclerView = (RecyclerView) findViewById(R.id.recyclerview);
GridLayoutManager glm = new GridLayoutManager(getContext(), 2);
glm.setSpanSizeLookup(new GridLayoutManager.SpanSizeLookup() {
    @Override
    public int getSpanSize(int position) {
        switch(sectionAdapter.getSectionItemViewType(position)) {
            case SectionedRecyclerViewAdapter.VIEW_TYPE_HEADER:
                return 2;
            default:
                return 1;
        }
    }
});
recyclerView.setLayoutManager(glm);
recyclerView.setAdapter(sectionAdapter);

Вы можете увидеть полный код здесь, макеты также доступны в репозитории.

Ответ 8

Я думаю, вам не нужно использовать несколько видов просмотра или компоновщика

Вы можете просто сделать логику в режиме ресайклера по позиции элемента. например, если в первом элементе нет кнопки воспроизведения и текстового представления времени, вы можете просто по умолчанию пометить свою видимость и когда вам понадобится эта кнопка воспроизведения и текстовый вид времени в этой позиции, вы можете сделать ее видимой.

например, у вас есть макет видео во второй позиции, а затем в методе get view вы получаете позицию, в которой вы можете сделать логику этого видимым.

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

Попробуйте эту логику, надеюсь, что она поможет вам