简体   繁体   中英

How to override @override method from activity into another class

Hi let's say I have an activity

class AcitivityA {


    @Override
    public void onConfigurationChanged(Configuration newConfig) {
        super.onConfigurationChanged(newConfig);
        // Do something
    }


}

And I have a class name

class myClass {


    private Activity current_activity;


    myClass(Activity activity) {
        current_activity = activity;
    }
}

So my question is, is there a way i can override onConfigurationChanged and put it into my class myClass?

So my goal is that I want to detect if the orientation is change

But I want it to be inside the class myClass

Create a Listener for that.

public interface OnChange() {
  void changed();
}

public class ListenerHolder {
    public static OnChange onChange = new OnChange( ... );
}

MyClass mClass = new MyClass();

@Override
public void onConfigurationChanged(Configuration newConfig) {
    super.onConfigurationChanged(newConfig);
    ListenerHolder.onChange.changed();
}

Take care that the interface should be static somewhere else then the own activity, else it may be destroyed with the activity.

But there are a few better ways solving that. BroadcastReceivers, Deeplinking, Extending, LiveData (Livecycle-aware), RxJava Subjects, ...

It's a bad design pattern to hook into view events outside a class which is not used for that.

Take a look at Android Architecture Components which uses a Mvvm Pattern including ViewModels and LiveData to survive configuration changes.

If you'r new to Android i highly recommend you to take a look at https://developer.android.com/topic/libraries/architecture/index.html for a proper design of your app. You may also start using Kotlin because it will be the maintained language in future for android.

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