1

I have the following activity with two integers

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()

    }
}

I want to change the value of the integer clubs from the fragment ClubsFragment when isScored is true

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
        }
    }
  }
}

I tried to use activity.clubs but It's not working. How can I access the activity constants from a fragment.

unknown1
  • 357
  • 1
  • 4
  • 10

1 Answers1

3

You would create an interface, let's say FragmentListener for your Activity that contains a function like fun updateClubs(count: Int). Your Activity should implement this interface. Then, in your Fragment, add a fragmentListener property and override onAttach(context: Context):

private var fragmentListener: FragmentListener? = null

override fun onAttach(context: Context) {
    this.listener = context as? FragmentListener
}

Then, in your OnClickListener, you can simply call fragmentListener?.updateClubs(4).

Dominik G.
  • 610
  • 3
  • 7