android-studio - Android 作用域传递问题?
PHP中文网
PHP中文网 2017-04-17 17:44:33
0
9
450

我在写App的时候好多Activity都在做同一个事情,就是操作各个Activity的界面的同一个部分。
所以我希望把这些做同一个事情的相同代码拿出来做一个类的静态方法,下次需要做这个事情就直接调用,不要重复写同样的代码。
于是我这样做的:

就这样把Context传递过去了,但是获取不到那个Context的变量和方法,这个应该怎么实现啊?
难道我必须要在几个Activity写出相同的代码?

PHP中文网
PHP中文网

认证高级PHP讲师

reply all(9)
PHPzhong

1. Abstract the same method into BaseActivity.

Ty80

You can write shared code in Activity A, and then the Activity that needs to use the shared code inherits Activity A

Ty80

You can use Mvp mode to put the same part of the logical control layer into the Present layer for management.

阿神
if(c instanceof MainActivity){
    ((MainActivity) c).colorfulPanelTimerTask = new TimerTask(){
        ...
    }
}
伊谢尔伦

Can you tell me what this method is used for? Because your return is similar to void, you must do something through contxt

Peter_Zhu

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.

洪涛

You haven’t gotten started with Java yet, lay the foundation first

黄舟

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)

刘奇

Write an abstract parent class. Put the shared methods in there.

Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template