我有两个整数的以下活动
class ComplexActivity : AppCompatActivity() {
var clubs : Int = 0
var diamonds : Int = 0
override fun onCreate(savedInstanceState: Bundle?) {
super.onCreate(savedInstanceState)
setContentView(R.layout.activity_complex)
val fragment = ClubsFragment()
val transaction = supportFragmentManager.beginTransaction()
transaction.replace(R.id.main_frame, fragment)
transaction.commit()
}
}
当isScored为true时,我想从片段ClubsFragment更改整数俱乐部的值
class ClubsFragment : Fragment(), SeekBar.OnSeekBarChangeListener{
private var isScored = false
override fun onCreateView(inflater: LayoutInflater?, container: ViewGroup?,
savedInstanceState: Bundle?): View? {
// Inflate the layout for this fragment
val v = inflater!!.inflate(R.layout.fragment_clubs, container, false)
v.image_clubs.setOnClickListener {
if(isScored){
activity.clubs = 4
}
}
}
}
我尝试使用activity.clubs但它不起作用。如何从片段中访问活动常量。
答案 0 :(得分:2)
您可以为包含FragmentListener
之类功能的Activity创建一个界面,让我们说fun updateClubs(count: Int)
。您的Activity应该实现此接口。
然后,在Fragment中,添加一个fragmentListener属性并覆盖onAttach(context:Context):
private var fragmentListener: FragmentListener? = null
override fun onAttach(context: Context) {
this.listener = context as? FragmentListener
}
然后,在OnClickListener中,您只需调用fragmentListener?.updateClubs(4)
。