Home > Blockchain >  Implements inner Fragment class in parent Activity
Implements inner Fragment class in parent Activity

Time:10-09

I have the following code:

public class SettingsActivity extends AppCompatActivity implements SettingsActivity.SettingsFragment.SendToActivity {
  ...
  public static class SettingsFragment extends PreferenceFragmentCompat {
    
    SendToActivity callback;

    public void setSendToActivity (SendToActivity callback) {
      this.callback = callback;
    }

    public interface SendToActivity {
      public void send(int result);
    }
    ...
  }

  @Override
  public void onAttachFragment(Fragment fragment) {
    if (fragment instanceof SettingsFragment) {
      SettingsFragment settingsFragment = (SettingsFragment) fragment;
      settingsFragment.setSendToActivity(this);
    }
  }

  public void send(int result) {
    ...
  }
}

But I get the following error: cyclic inheritance involving SettingsActivity in the the declaration of the SettingsActivity class. What I'm doing wrong?

CodePudding user response:

Try moving SendToActivity out of SettingsFragment, such as:

public class SettingsActivity extends AppCompatActivity implements SettingsActivity.SendToActivity {
  public interface SendToActivity {
    public void send(int result);
  }

  ...

  public static class SettingsFragment extends PreferenceFragmentCompat {
    
    SendToActivity callback;

    public void setSendToActivity (SendToActivity callback) {
      this.callback = callback;
    }

    ...

  }

  @Override
  public void onAttachFragment(Fragment fragment) {
    if (fragment instanceof SettingsFragment) {
      SettingsFragment settingsFragment = (SettingsFragment) fragment;
      settingsFragment.setSendToActivity(this);
    }
  }

  public void send(int result) {
    ...
  }
}

CodePudding user response:

I answer myself: The fragment class needs to be on its own java file. Then just implement it normally (implements SettingsFragment.SendToActivity).

  • Related