TabLayout + ViewPager - Не отображать содержимое фрагмента на каждой странице - PullRequest
0 голосов
/ 22 октября 2019

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

Может кто-нибудь указать мне, что мне не хватает?

activity_main.xml

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

    <com.google.android.material.appbar.AppBarLayout
        android:id="@+id/appBar"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:theme="@style/AppTheme.AppBarOverlay">

        <androidx.appcompat.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

        <include
            android:id="@+id/totalSection"
            layout="@layout/fragment_total"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="?attr/actionBarSize" />

        <com.google.android.material.tabs.TabLayout
            android:id="@+id/tab_layout"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            app:tabRippleColor="@color/colorPrimary">

            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

            <com.google.android.material.tabs.TabItem
                android:layout_width="wrap_content"
                android:layout_height="wrap_content" />

        </com.google.android.material.tabs.TabLayout>

    </com.google.android.material.appbar.AppBarLayout>

    <androidx.viewpager.widget.ViewPager
        android:id="@+id/viewPager"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        app:layout_behavior="@string/appbar_scrolling_view_behavior" />

    <!-- floating action button here -->

</androidx.coordinatorlayout.widget.CoordinatorLayout>

MainActivity.kt

override fun onCreate(savedInstanceState: Bundle?) {
    Log.d("MainActivity", "OnCreate")
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)
    setSupportActionBar(toolbar)

    viewPager.adapter = SectionsPageAdapter(this, supportFragmentManager)
    tab_layout.setupWithViewPager(viewPager)
    ...
}

Адаптер

class SectionsPageAdapter(private val context: Context, fm: FragmentManager) :
    FragmentPagerAdapter(fm, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {
    private val tabTitles = arrayOf("Participants", "Consumptions")

    override fun getItem(position: Int): Fragment {
        Log.d("SectionsPageAdapter", "getItem")
        return ItemDetailsListFragment(context, position)
    }

    override fun isViewFromObject(view: View, obj: Any): Boolean {
        return view == obj
    }

    override fun getCount(): Int {
        return 2
    }

    override fun getPageTitle(position: Int): CharSequence? {
        return tabTitles[position]
    }
}

Фрагмент

class ItemDetailsListFragment(private val ctx: Context, private val position: Int) : Fragment() {

    override fun onCreateView(
        inflater: LayoutInflater,
        container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        Log.d("ItemDetailsListFragment", "OnCreateView")
        val root =  inflater.inflate(R.layout.fragment_items, container, false)
        root.findViewById<TextView>(R.id.test).text = "Test"
        return root
    }
 }

фрагмент_items.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"
    android:layout_width="match_parent"
    android:layout_height="match_parent"
    android:orientation="vertical">

    <!--
    <ListView
        android:id="@+id/mList"
        android:layout_width="match_parent"
        android:layout_height="wrap_content"
        android:divider="@drawable/list_divider"
        android:footerDividersEnabled="false"
        android:scrollbars="none" />
    -->

    <TextView
        android:id="@+id/test"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="TextView"
        app:layout_constraintLeft_toLeftOf="parent"
        app:layout_constraintTop_toTopOf="parent" />
</androidx.constraintlayout.widget.ConstraintLayout>

enter image description here

Ответы [ 2 ]

0 голосов
/ 22 октября 2019

Решил это. Мне просто нужно было удалить этот метод

 override fun isViewFromObject(view: View, obj: Any): Boolean {
    return view == obj
}

Похоже, я работал с одним ListView, используя два разных типа View, и забыл удалить этот метод.

0 голосов
/ 22 октября 2019

Можете ли вы попытаться добавить некоторые ограничения в ViewPager:

<androidx.viewpager.widget.ViewPager
    android:id="@+id/viewPager"
    android:layout_width="match_parent"
    android:layout_height="0dp"
    app:layout_constraintTop_toBottomOf="@id/appBar"
    app:layout_constraintBottom_toBottomOf="parent"
    app:layout_behavior="@string/appbar_scrolling_view_behavior" />
...