android 的全局变量,Android全局变量

There are a few different ways you can achieve what you are asking for.

1.) Extend the application class and instantiate your controller and model objects there.

public class FavoriteColorsApplication extends Application {

private static FavoriteColorsApplication application;

private FavoriteColorsService service;

public FavoriteColorsApplication getInstance() {

return application;

}

@Override

public void onCreate() {

super.onCreate();

application = this;

application.initialize();

}

private void initialize() {

service = new FavoriteColorsService();

}

public FavoriteColorsService getService() {

return service;

}

}

Then you can call the your singleton from your custom Application object at any time:

public class FavoriteColorsActivity extends Activity {

private FavoriteColorsService service = null;

private ArrayAdapter adapter;

private List favoriteColors = new ArrayList();

@Override

protected void onCreate(Bundle savedInstanceState) {

super.onCreate(savedInstanceState);

setContentView(R.layout.activity_favorite_colors);

service = ((FavoriteColorsApplication) getApplication()).getService();

favoriteColors = service.findAllColors();

ListView lv = (ListView) findViewById(R.id.favoriteColorsListView);

adapter = new ArrayAdapter(this, R.layout.favorite_colors_list_item,

favoriteColors);

lv.setAdapter(adapter);

}

2.) You can have your controller just create a singleton instance of itself:

public class Controller {

private static final String TAG = "Controller";

private static sController sController;

private Dao mDao;

private Controller() {

mDao = new Dao();

}

public static Controller create() {

if (sController == null) {

sController = new Controller();

}

return sController;

}

}

Then you can just call the create method from any Activity or Fragment and it will create a new controller if one doesn't already exist, otherwise it will return the preexisting controller.

3.) Finally, there is a slick framework created at Square which provides you dependency injection within Android. It is called Dagger. I won't go into how to use it here, but it is very slick if you need that sort of thing.

I hope I gave enough detail in regards to how you can do what you are hoping for.

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值