1

Проблема заключается в том, что у меня не отображается содержимое ViewPager. Я даже попытался найти подходящий проект на Java и переписать на Kotlin. Все проекты на Java отлично отображают ViewPager, с Kotlin не получается.

Разметка главное активности:

<RelativeLayoutxmlns: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=".MainActivity">

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

Разметка view_pager_item:

    <LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical">

<ImageView
    android:id="@+id/imageView"
    android:layout_marginTop="50dp"
    android:layout_marginLeft="@dimen/activity_horizontal_margin"
    android:layout_marginRight="@dimen/activity_horizontal_margin"
    android:paddingTop="8dp"
    android:paddingBottom="8dp"
    android:layout_width="match_parent"
    android:layout_height="@dimen/ob_banner_height"
    android:gravity="center"
    android:scaleType="fitXY"
    android:src="@drawable/first_image_item"
    android:contentDescription="@string/app_name"/>

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

        <TextView
            android:id="@+id/textViewTitle"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:gravity="center"
            android:paddingLeft="@dimen/ob_desc_padding"
            android:paddingRight="@dimen/ob_desc_padding"
            android:text="@string/app_name"
            android:textAllCaps="true"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/ob_header_text_size" />

        <TextView
            android:id="@+id/textViewDescription"
            android:layout_width="match_parent"
            android:layout_height="wrap_content"
            android:layout_marginTop="20dp"
            android:gravity="center"
            android:paddingLeft="@dimen/ob_desc_padding"
            android:paddingRight="@dimen/ob_desc_padding"
            android:text="@string/app_name"
            android:textColor="@color/colorAccent"
            android:textSize="@dimen/ob_desc_text_size" />
    </LinearLayout>

Код ViewPagerAdapter:

   class ViewPagerAdapter(private var context: Context, private var viewPagerItems: ArrayList<ViewPagerItem>): PagerAdapter() {

override fun getCount() = viewPagerItems.size

override fun isViewFromObject(view: View, `object`: Any) = `object` === Any()

override fun instantiateItem(container: ViewGroup, position: Int): Any {
    val view = LayoutInflater.from(context).inflate(R.layout.view_pager_item, container, false)

    val item = viewPagerItems[position]

    val imageView = view.findViewById<ImageView>(R.id.imageView)
    imageView.setImageResource(item.imageId)

    val textViewTitle = view.findViewById<TextView>(R.id.textViewTitle)
    textViewTitle.text = item.title

    val textViewDescription = view.findViewById<TextView>(R.id.textViewDescription)
    textViewDescription.text = item.description

    container.addView(view)

    return view
}

override fun destroyItem(container: ViewGroup, position: Int, `object`: Any) {
    container.removeView(`object` as LinearLayout)
}

}

ViewPagerItem это обычный дата-класс:

    data class ViewPagerItem(
    val imageId: Int,
    val title: String,
    val description: String)

Наконец, главный класс:

    class MainActivity : AppCompatActivity() {

private lateinit var viewPagerAdapter: ViewPagerAdapter
private lateinit var viewPager: ViewPager
private lateinit var buttonNext: Button

private lateinit var pagerIndicator: LinearLayout
private lateinit var dots: Array<ImageView?>

private var previousPosition = 0
private var dotsCount: Int = 3

private var viewPagerItems: ArrayList<ViewPagerItem> = arrayListOf()


override fun onCreate(savedInstanceState: Bundle?) {
    super.onCreate(savedInstanceState)
    setContentView(R.layout.activity_main)

    buttonNext = findViewById(R.id.buttonNext)
    viewPager = findViewById(R.id.viewPager)
    pagerIndicator = findViewById(R.id.viewPagerDots)

    initializeData()

    viewPagerAdapter = ViewPagerAdapter(this, viewPagerItems)
    viewPager.adapter = viewPagerAdapter

    setUiViewPagerController()

    viewPager.currentItem = 0
    viewPager.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
        override fun onPageScrolled(position: Int, positionOffset: Float, positionOffsetPixels: Int) {}

        override fun onPageSelected(position: Int) {
            for (i in 0 until dotsCount) {
                dots[i]?.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.non_selected_view_pager_item))
            }

            dots[position]?.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.selected_view_pager_item))


            val pos = position + 1

            if (pos == dotsCount && previousPosition == dotsCount - 1)
                showAnimation()
            else if (pos == dotsCount - 1 && previousPosition == dotsCount)
                hideAnimation()

            previousPosition = pos
        }

        override fun onPageScrollStateChanged(state: Int) {}
    })

    buttonNext.setOnClickListener {
        Toast.makeText(this@MainActivity, "Redirect to wherever you want", Toast.LENGTH_LONG).show()
    }
}

private fun initializeData() {
    val titles = intArrayOf(R.string.app_name, R.string.app_name, R.string.app_name)
    val descriptions = intArrayOf(R.string.app_name, R.string.app_name, R.string.app_name)
    val images = intArrayOf(R.drawable.first_image_item, R.drawable.onboard_page2, R.drawable.onboard_page3)

    for (i in images.indices) {
        val item = ViewPagerItem(
                images[i],
                resources.getString(titles[i]),
                resources.getString(descriptions[i]))

        viewPagerItems.add(item)
    }
}

fun showAnimation() {
    ...
}

fun hideAnimation() {
    ...
}

private fun setUiViewPagerController() {
    dotsCount = viewPagerAdapter.count
    dots = arrayOfNulls(dotsCount)

    for (i in 0 until dotsCount) {
        dots[i] = ImageView(this)
        dots[i]?.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.non_selected_view_pager_item))

        val params = LinearLayout.LayoutParams(
                LinearLayout.LayoutParams.WRAP_CONTENT,
                LinearLayout.LayoutParams.WRAP_CONTENT
        )

        params.setMargins(6, 0, 6, 0)

        pagerIndicator.addView(dots[i], params)
    }

    dots[0]?.setImageDrawable(ContextCompat.getDrawable(this@MainActivity, R.drawable.selected_view_pager_item))
}

}

1 ответ 1

1

В коде ViewPagerAdapter изменить функцию:

override fun isViewFromObject(view: View, `object`: Any) = view == `object`

Ваш ответ

Нажимая «Отправить ответ», вы соглашаетесь с условиями пользования и подтверждаете, что прочитали политику конфиденциальности.

Всё ещё ищете ответ? Посмотрите другие вопросы с метками или задайте свой вопрос.