سؤال

How would I do this? Or is it even possible get a button within a fragment from the activity?

I've tried many things e.g. trying to get the view or container of the fragment but no luck.

I am doing this as i have 27 fragments in an activity which all have a same button. Instead of doing a button listener on each fragment, i want to reduce my code greatly but just doing a loop in my activity going through each fragment and setting there button to activate the button listener (in the activity) if pressed.

Once i know how to get a button and set it to the button listener, I can easily do the loop bit my self.

Just finishing my first year for computer science and have been coding in java for a couple of years now.

Thanks in advance!

هل كانت مفيدة؟

المحلول

Don't loop or get reference to the button.

Simply make your activity implement OnClickListener and set it as click listeners for the buttons in all your fragments .. In the fragment

yourBtn.setOnClickListener(((YourActivityType) getActivity()));

another solution without the implements keyword

is to have a public method in your activity, for example, setButtonAction(Button btn)

public void setButtonAction(Button btn) {
     btn.setOnClickListener(myClickListener);
}

and declare myClickListener as variable in youractivity

Same idea without having your activity to implement clickLitener

مرخصة بموجب: CC-BY-SA مع الإسناد
لا تنتمي إلى StackOverflow
scroll top