简体   繁体   中英

How to update textview of a fragment inside a ViewPager (Kotlin)

Suppose I have got a seek bar in the activity to change the textview font size of the fragment. What method should I pass?

I have an activity. This includes a view pager. The view pager has a pager adapter. For each item in the pager adapter, we create new instance of fragment. When I drag the SeekBar, I want to pass the value onto the fragment. I have applied interface callback and also passing argument bundle. But, when it comes to implementation and testing, the font size des not change.

Would you please advise me the way to pass one value from a seek bar of an activity to a fragment within the pager adapter ?

Here is my working :

class ChapterActivity : AppCompatActivity() , ViewPager.OnPageChangeListener  {

...


        val listener =  object : SeekBar.OnSeekBarChangeListener  {
            override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {

                val scaledSize =  progress * 0.6 + minimumValue
                println("scaledSize : $scaledSize"  )
                println("scaledSize : ${scaledSize.toFloat()}"  )
                //txt_chapter_content.setTextSize(TypedValue.COMPLEX_UNIT_DIP, scaledSize .toFloat() );
                val prefs = getPreferences(Context.MODE_PRIVATE)
                val ed = prefs.edit()
                ed.putFloat("fontsize", scaledSize.toFloat())
                ed.apply()

                val myBundle = Bundle()
                myBundle.putFloat("fontsize" , scaledSize.toFloat() )

                        mAboutDataListener!!.onDataReceived(scaledSize.toFloat())



            }

            override fun onStartTrackingTouch(seekBar: SeekBar?) {

            }

            override fun onStopTrackingTouch(seekBar: SeekBar?) {

            }
        }



            chapterPagerAdapter = ChapterPagerAdapter(supportFragmentManager, chapters)
       // Set the Adapter and the TabLayout forward the ViewPager
            chapterViewPager.adapter = chapterPagerAdapter
            chapterViewPager.addOnPageChangeListener(this);

Fragment:

    override fun onCreateView(
        inflater: LayoutInflater, container: ViewGroup?,
        savedInstanceState: Bundle?
    ): View? {
        // Inflate the layout forward this fragment
        val view = inflater.inflate(com.books.learn.ddy.blinkist.R.layout.content_chapter, container, false)
        val titleTextView = view.findViewById<TextView>(R.id.txt_chapter_title)
        val contextTextView = view.findViewById<TextView>(R.id.txt_chapter_content)

contextTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, floatSize )

override fun onDataReceived(fontSize: Float) {
    contextTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, fontSize );
}

You should implement a callback interface in the fragment while keeping a reference of this callback in your activity. This way when you call a function [suppose changeFontSize()] from your activity, your fragment's implementation of this method will be called. Check this answer

Keep in mind that when using ViewPager you will also have to check for current fragment visibility. Check this answer

Hope this helps.

If your PagerAdapter is not FragmentStatePagerAdapter,you can obtain your Fragment(eg FragmentOne) and update the scaled size as follows:

val page = getSupportFragmentManager().findFragmentByTag("android:switcher:${R.id.pager}:${pagerPosition}"
if (page != null) {
   ((FragmentOne)page).onDataReceived(scaledSize.toFloat())   
}

If not feasible,check here to know how to get the Fragment instance in the viewpager,then just call it's method in activity.

I have posted an answer to a similar question here https://stackoverflow.com/a/60427448/2102794 .

Fragment

class SampleFragment : Fragment(), BaseFragmentInteraction {
    override fun updateSeekBarProgress(progress: Int) {
        Toast.makeText(activity!!, data, Toast.LENGTH_SHORT).show()
    }
}

Interface

interface BaseFragmentInteraction {
    fun updateSeekBarProgress(progress: Int)
}

SeekBar Callback:

val listener = object : SeekBar.OnSeekBarChangeListener {
    override fun onProgressChanged(seekBar: SeekBar?, progress: Int, fromUser: Boolean) {
        val fragmentItem = (view_pager.adapter as FragmentPagerAdapter).getItem(view_pager.currentItem)
        (fragmentItem as BaseFragmentInteraction).updateSeekBarProgress(progress)
    }
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM