简体   繁体   中英

Android - How to properly get a variable from a parent activity from a fragment

I read the official Android documentation on creating an interface to be able to communicate between a parent activity and a fragment. So I did but my app crashes when I call one of the methods to get a value from the parent activity.

if have an interface like this in my fragment

public interface InteractWithFragmentA { String getStringText(); }

In my calling activity I tested it out with a dummy text

@Override 
public String getStringText(){ return "Some dummy text";}

I have a variable in FragmentA.java that's a reference to the host activity and casted to InteractWithFragmentA, but when I call the method using

_hostActivity.getStringText()

the app crashes. Is there something that I'm missing? I've seen some suggested methods for getting the host activity's variables by making them public and static or some other method but I'm trying not to couple the fragment to that activity. Thanks in advance.

Yo should do this:

Activity

 public class YourActivity implements YourActivityInterface{
     @Override   public String getStringText(){ return "Some dummy text";}
 }

Interface

    public interface YourActivityInterface {
    String getStringText(); 
}

Fragment

  public class YourFragment extends Fragment {

    YourActivityInterface mListener;

     //your method...
     mListener.getStringText()


@Override
    public void onAttach(Context context) {
        super.onAttach(context);
        if (context instanceof YourActivityInterface) {
            mListener = (YourActivityInterface) context;
        } else {
            throw new RuntimeException(context.toString()
                    + " must implement YourActivityInterface");
        }
    }

    @Override
    public void onDetach() {
        super.onDetach();
        mListener = null;
    }
    }

从片段尝试

((YourActivity) getActivity()).getStringText();

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