Reputation: 485
How to access Button inside Activity from Fragment. Actually I set myButton is disabled but when some of my radioButtons was clicked i want to set myButton enabled?
Upvotes: 2
Views: 3149
Reputation: 12596
Here is an example:
In MyFragment.java
public MyFragment extends Fragment {
public interface Callback {
public void onRadioButtonClicked(View radioButton);
}
private Callback callback;
@Override
public void onAttach(Activity ac) {
super.onAttached(ac);
callback = (Callback)ac;
}
@Override
public void onDetach() {
callback = null;
super.onDetach();
}
....
....
radioButton.setOnClickListener(new OnClickListener() {
public void onClick(View view) {
if (callback != null) {
callback.onRadioButtonClicked(view);
}
}
});
}
And in MyActivity.java that hosts/contains a MyFragment:
public MyActivity extends Activity implements MyFragment.Callback {
...
@Override
public void onRadioButtonClicked(View radioButton) {
// The radiobutton in MyFragment has been clicked
myButton.setEnabled(true); // or something like this.
}
}
This design uses the MyFragment.Callback
interface to keep details of the hosting Activity away from the Fragment, allowing the Fragment to be hosted by any Activity as long as the Activity implements MyFragment.Callback
.
Upvotes: 4
Reputation: 3785
There are a few things you could try. The first one is to use getActivity().findViewByIt(id)
to get the Button
, which I think should work but it's not a good solution from the engineering side of things since your Fragment
would make assumptions about the Activity
layout that hosts it. The second would be to provide a callback interface as described here. Just call the callback method every time the checkbox changes state. This approach is better since the Fragment
can be freely re-used by any activity that implements the callback interface. Last but not least, you should try to put the Button
inside the fragment if at all possible.
Upvotes: 5