使用 setUserVisibleHint 方法判断 Fragment 是否可见

场景:ViewPager中嵌套多个Fragment,判断Fragment是否可见

以下为Kotlin代码

MainActivity.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
package xyz.hanks.fragmentvisiable

import android.os.Bundle
import android.support.v4.app.Fragment
import android.support.v4.app.FragmentManager
import android.support.v4.app.FragmentPagerAdapter
import android.support.v7.app.AppCompatActivity
import kotlinx.android.synthetic.main.activity_main.*

var fragmentList: List<Fragment> ? = null

class MainActivity : AppCompatActivity() {
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_main)
fragmentList = listOf<Fragment>(Fragment01(),Fragment02(),Fragment03()) // 创建Fragment集合
viewPager.adapter = MainFragmentPageAdapter(supportFragmentManager) // 给ViewPager设置Adapter
}
}

internal class MainFragmentPageAdapter(fragmentManager: FragmentManager) : FragmentPagerAdapter(fragmentManager) {
override fun getItem(p0: Int): Fragment? = fragmentList?.get(p0)
override fun getCount(): Int = fragmentList!!.size
}

使用了 Kotlin 的特性,代码简洁很多。

layout_main.xml

1
2
3
4
5
6
7
8
9
10
11
12
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="https://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent">

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

Fragment02.kt

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
package xyz.hanks.fragmentvisiable

import android.os.Bundle
import android.support.v4.app.Fragment
import android.util.Log
import android.util.TypedValue
import android.view.LayoutInflater
import android.view.View
import android.view.ViewGroup
import android.widget.TextView

/**
* Created by hanks on 16/3/8.
*/
class Fragment02 : Fragment(){

override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?, savedInstanceState: Bundle?): View? {
val view = TextView(context)
view.text = "Fragment02"
view.setTextSize(TypedValue.COMPLEX_UNIT_SP,30f)
return view
}

// 重写 setUserVisibleHint
override fun setUserVisibleHint(isVisibleToUser: Boolean) {
super.setUserVisibleHint(isVisibleToUser)
Log.d("Fragment","Fragment02 $isVisibleToUser") // 打印isVisibleToUser
}
}

Fragment01 Fragment03与Fragment02类似

gif

结果:

1
2
3
`启动时`:                : 03-08 10:18:19.238 20377-20377/xyz.hanks.fragmentvisiable D/Fragment: Fragment02 false
`Fragment01->Fragment02` : 03-08 10:19:15.586 20377-20377/xyz.hanks.fragmentvisiable D/Fragment: Fragment02 true
`Fragment02->Fragment03` : 03-08 10:20:01.038 20377-20377/xyz.hanks.fragmentvisiable D/Fragment: Fragment02 false

文章来自: https://hanks.pub