简体   繁体   English

如何将@override方法从活动覆盖到另一个类

[英]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? 所以我的问题是,有没有办法可以覆盖onConfigurationChanged并将其放入我的类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 但我希望它位于类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, ... 广播接收器,深层链接,扩展,LiveData(可感知Livecycle的),RxJava主题,...

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. 看一下使用Mvvm模式(包括ViewModels和LiveData)以保留配置更改的Android体系结构组件

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. 如果您是Android的新手,我强烈建议您访问https://developer.android.com/topic/libraries/architecture/index.html ,以正确设计应用程序。 You may also start using Kotlin because it will be the maintained language in future for android. 您也可能会开始使用Kotlin,因为它将成为Android将来的维护语言。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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