另一个ViewPager内的ViewPager中的项目存在问题

时间:2019-04-26 04:11:14

标签: android kotlin android-viewpager

我正在创建电影应用。目前,我正在RecyclerView中的Fragment中显示所有电影项目。当用户单击特定的电影项目时,ListFragmentDetailsFragment取代。我可以从DetailsFragment滑动到下一个项目,所以我在这里使用了ViewPager。在DetailsFragment中,我有一个ImageView和一个TextViewImageView包含电影的图像。我正在使用Glide加载图像。电影项目可以包含电影的多个图像。我使用了另一个ViewPager在图像之间交换。我已经完成了所有这些工作,没有任何问题。但是,问题开始于我想用原始宽高比调整电影图像的大小时。图像没有调整其应有的大小。滑动嵌套的ViewPager时,通常会根据下一项或上一项的尺寸来调整图像的大小。

每当用户单击ListFragment中的一个项目时,我就会用来自ViewPager的所有电影项目填充前一个Activity并将setCurrent项目设置为被单击的项目。然后,我以阵列的形式拍摄该电影的所有图像,获取它们的bitmap,根据设备大小计算新的宽度和高度,并调整bitmap的大小。然后,我将这些图像发送到嵌套的ViewPager。但是,假设我有一部电影的三张图片,而第二张图片的尺寸已根据第一张或第三张图片的长宽比进行了调整。

在“ MainActivity”中,我正在创建一些电影项目并附加ListFragment

movieList = mutableListOf()

        val movie = setMovie(
            "1",
            "Fight Club",
            "A movie worth watching",
            "https://m.media-amazon.com/images/M/MV5BMjJmYTNkNmItYjYyZC00MGUxLWJhNWMtZDY4Nzc1MDAwMzU5XkEyXkFqcGdeQXVyNzkwMjQ5NzM@._V1_SY1000_CR0,0,676,1000_AL_.jpg",
            "https://www.rollingstone.com/wp-content/uploads/2018/06/rs-19014-fightclub-1800-1406035542.jpg?crop=900:600&width=1440",
            "https://cdn-static.denofgeek.com/sites/denofgeek/files/styles/main_wide/public/2017/02/fight-club_main.jpg?itok=rdIIiUuT"
        )

        val movie1 = setMovie(
            "2",
            "The Shawshank Redemption",
            "A movie worth watching",
            "https://files.kstatecollegian.com/2015/06/c4728ae2-cf07-4ae6-af7e-34cf3cb38dbe-696x1044.jpg",
            "https://i0.wp.com/www.moviehousememories.com/wp-content/uploads/2014/03/The-Shawshank-Redemption-2.jpg?w=1278&ssl=1",
            "https://static1.squarespace.com/static/51b3dc8ee4b051b96ceb10de/t/5b3e33e270a6ad4a13a68537/1530803174357/?format=1500w"
        )

        val movie2 = setMovie(
            "3",
            "Titanic",
            "A movie worth watching",
            "https://m.media-amazon.com/images/M/MV5BMTg4MzQxMjIyNV5BMl5BanBnXkFtZTcwOTA3NTk1Nw@@._V1_SY1000_CR0,0,1380,1000_AL_.jpg",
            "https://upload.wikimedia.org/wikipedia/commons/thumb/f/fd/RMS_Titanic_3.jpg/800px-RMS_Titanic_3.jpg",
            "https://imgix.bustle.com/uploads/image/2017/6/23/23e8ab61-7603-4bf3-bbed-00818829afd1-titanic.png?w=970&h=546&fit=crop&crop=faces&auto=format&q=70"
        )

        movieList.add(movie)
        movieList.add(movie1)
        movieList.add(movie2)

        val fragment = FirstFragment()
        supportFragmentManager.beginTransaction().replace(R.id.frame_layout, fragment).commit()

Movie的模型类:

    var id: String? = ""
    var name: String? = ""
    var desc: String? = ""
    var image1: String? = ""
    var image2: String? = ""
    var image3: String? = ""

ListFragment又称FirstFragment: `

    recyclerView.setHasFixedSize(true)

    val layoutManager = LinearLayoutManager(context)
    recyclerView.layoutManager = layoutManager

    adapter = CustomAdapter(activity!!, (activity as MainActivity).movieList)
    recyclerView.adapter = adapter

`

FirstFragmentListFragment的适配器:

override fun onBindViewHolder(p0: ViewHolder, p1: Int) {
        p0.textView.text = movieList[p1].name

        p0.itemView.setOnClickListener {
            val fragment = SecondFragment()
            val bundle = Bundle()
            bundle.putInt("pos", p1)
            fragment.arguments = bundle
            val transaction = (activity as FragmentActivity).supportFragmentManager.beginTransaction()
            transaction.addToBackStack(null)
            transaction.replace(R.id.frame_layout, fragment)
            transaction.commit()
        }
    }

现在,SecondFragment保留了第一个ViewPager

val adapter = ItemAdapter(childFragmentManager, (activity as MainActivity).movieList)
        viewPager.adapter = adapter

        val bundle = arguments
        if (bundle != null) {
            position = bundle.getInt("pos")
            viewPager.setCurrentItem(position, true)
        }

现在,第一个ViewPager的适配器:

class ItemAdapter(
    fm: FragmentManager?,
    val movieList: MutableList<Movie>
) : FragmentStatePagerAdapter(fm) {
    override fun getItem(p0: Int): Fragment {
        val fragment = ThirdFragment()
        val bundle = Bundle()
        bundle.putParcelable("movie", movieList[p0])
        fragment.arguments = bundle
        return fragment
    }

    override fun getCount(): Int {
        return movieList.size
    }
}

现在,DetailsFragment又名ThirdFragment(其中包含嵌套的ViewPager):

images = mutableListOf()
        allItems = mutableListOf()

        val bundle = arguments
        if (bundle != null) {
            val movie = bundle.getParcelable("movie") as Movie

            images.add(movie.image1!!)
            images.add(movie.image2!!)
            images.add(movie.image3!!)

            for (i in 0 until images.size) {
                val fetchData = FetchData()
                fetchData.asyncResponse = this
                fetchData.execute(images[i])
            }

            tvName.text = movie.name
        }

        adapter = AnotherAdapter(childFragmentManager, allItems)
        viewPager.adapter = adapter

        return view
    }

    override fun processFinish(imageProperty: ImageProperty) {
        val width = imageProperty.bitmap!!.width
        val height = imageProperty.bitmap!!.height
        val originalRatio: Double = width.toDouble() / height.toDouble()

        val deviceWidth = viewPager.measuredWidth
        val scaledHeight = deviceWidth.toDouble() / originalRatio

        imageProperty.width = deviceWidth
        imageProperty.height = scaledHeight.toInt()

        Methods().showLog("Link: ${imageProperty.link!!}")
        Methods().showLog("Width: ${imageProperty.width}")
        Methods().showLog("Height: ${imageProperty.height}")

        allItems.add(imageProperty)
        adapter = AnotherAdapter(childFragmentManager, allItems)
        viewPager.adapter = adapter
    }

    class FetchData : AsyncTask<String, Void, ImageProperty>() {
        var asyncResponse: ImageResponse? = null
        override fun doInBackground(vararg params: String?): ImageProperty {
            return try {
                val url = URL(params[0])

                val connection = url
                    .openConnection() as HttpURLConnection
                connection.doInput = true
                connection.connect()
                val input = connection.inputStream
                val imageProperty = ImageProperty()
                imageProperty.link = params[0]
                imageProperty.bitmap = BitmapFactory.decodeStream(input)
                imageProperty
            } catch (e: IOException) {
                e.printStackTrace()
                val imageProperty = ImageProperty()
                imageProperty.bitmap = BitmapFactory.decodeStream(null)
                imageProperty
            }
        }

        override fun onPostExecute(result: ImageProperty?) {
            super.onPostExecute(result)
            asyncResponse?.processFinish(result!!)
        }
    }

ImageProperty的模型类:

class ImageProperty() : Parcelable {
    var link: String? = ""
    var width: Int = 0
    var height: Int = 0
    var bitmap: Bitmap? = null

嵌套ViewPager的适配器:

class AnotherAdapter(fm: FragmentManager?, private val list: MutableList<ImageProperty>) : FragmentStatePagerAdapter(fm) {
    override fun getItem(p0: Int): Fragment {
        val fragment = FourthFragment()
        val bundle = Bundle()
        bundle.putParcelable("image", list[p0])
        fragment.arguments = bundle
        return fragment
    }

    override fun getCount(): Int {
        return list.size
    }
}

最后,最后一个用于显示图像的片段(当前,我没有使用ImageView,而是使用TextView来检查图像的大小是否正确。它们是否正确地调整了大小。但是如果您检查ViewPager,它没有按照TextView中的尺寸进行调整,而是按照下一项或上一项进行调整):

val bundle = arguments
        val imageProperty = bundle!!.getParcelable("image") as ImageProperty

        val textView2 = view.findViewById<TextView>(R.id.textView2)
        val textView3 = view.findViewById<TextView>(R.id.textView3)
        val textView4 = view.findViewById<TextView>(R.id.textView4)

        textView2.text = imageProperty.link
        textView3.text = imageProperty.width.toString()
        textView4.text = imageProperty.height.toString()

        (parentFragment as ThirdFragment).viewPager.layoutParams.width = imageProperty.width
        (parentFragment as ThirdFragment).viewPager.layoutParams.height = imageProperty.height
        (parentFragment as ThirdFragment).viewPager.requestLayout()

0 个答案:

没有答案