我在写App的时候好多Activity都在做同一个事情,就是操作各个Activity的界面的同一个部分。
所以我希望把这些做同一个事情的相同代码拿出来做一个类的静态方法,下次需要做这个事情就直接调用,不要重复写同样的代码。
于是我这样做的:
就这样把Context传递过去了,但是获取不到那个Context的变量和方法,这个应该怎么实现啊?
难道我必须要在几个Activity写出相同的代码?
PHP中文网2017-04-17 17:46:33
You can write shared code in Activity A, and then the Activity that needs to use the shared code inherits Activity A
PHP中文网2017-04-17 17:46:33
You can use Mvp mode to put the same part of the logical control layer into the Present layer for management.
阿神2017-04-17 17:46:33
if(c instanceof MainActivity){
((MainActivity) c).colorfulPanelTimerTask = new TimerTask(){
...
}
}
伊谢尔伦2017-04-17 17:46:33
Can you tell me what this method is used for? Because your return is similar to void, you must do something through contxt
天蓬老师2017-04-17 17:46:33
If the same part of your code is the interface and the corresponding logic, just use Fragment. Why do you need to pass it? The Context is generally passed only to use the Context method, rather than down-converting to a specific Activity, which is too coupled. If the same part of code is a small piece of code, put the code in a BaseActivity and let other activities inherit it.
黄舟2017-04-17 17:46:33
1. If it is a public method and the functions implemented are the same:
Write a base class of Activity, BaseActivity, and write the public method in the base class for subclasses to call.
2. If the functions implemented by the public methods are different, the method names must be the same. :
The same method is to create the base class BaseActivity and write an abstract method. The specific implementation is completed in the subclass
PS: Passing context will definitely not get the objects in the Activity. At least you must write ((Activity)context)