简体   繁体   中英

How to access Button inside Activity from Fragment

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?

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.

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM