如何调用一个“方法”中的另一项活动定义上点击的小窗口按钮? [英] How to call a 'method' defined in another activity on click of a widget button?

查看:139
本文介绍了如何调用一个“方法”中的另一项活动定义上点击的小窗口按钮?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我知道如何启动活动上点击使用挂起的意图插件按钮,但我想打电话给该活动的具体方法。

I know how to launch an activity on click of widget button using pending intent but I want to call a particular method of that activity.

推荐答案

如果您需要调用在另一个活动那么你下面一个错误的设计方法。你不应该把所有的code。在活动孤单。

If you need to call a method in another activity then you're following a wrong design. You should not put all of your code in the activities alone.

为什么它是一个不错的选择 -
因为你需要的类的对象调用一个方法就可以了。而你将如何得到活动的对象呢?除非你存储一个活动的对象到另一个(这是一个pretty的乱七八糟的事情)。在这种方法的另一个问题是,你的其他活动可能已经被破坏了,所以如果你依赖于一些其他活动的UI元素,那么你会得到没有帮助。使静态的活动将打开一个巨大的蠕虫可以为你。

Why it's a bad choice -
Because you need an object of the class to call a method on it. And how would you get an object of the activity? Unless you are storing the object of one activity into another (That's a pretty messed up thing to do). Another problem in this approach is your other activity might have been destroyed already, so if you're relying on some of the UI element of another activity then you'll get no help at all. Making the activities static will open a huge can of worms for you.

有啥可选项 -
这里是很多可用做内部活动的方法调用的选项,但我靠Singletons.They是可以有哪些是静态访问只有一个对象类,所以你不会有存储类的一个对象任何地方,因为类本身存储的对象。它可以像下面 -

So What's the option available -
There're a lot of options available for doing inter-activity method calls, but I rely on Singletons.They are classes which can have only one object which will be accessed statically, so you won't have to store an object of the class anywhere, since the class itself stores the object. It can go like the following -

public class AppManager{
  private static AppManager _instance = null;
  public static AppManager getInstance(){
    if(_instance == null)
      _instance= new AppManager();
    return _instance;
  }
  private AppManager(){} //Making the constructor private, so no 2 object can be created
  public void someMethod(){}
}

所以为了叫的someMethod()从项目中的任何地方你只需要调用

So in order to call someMethod() from any where in your project you'll just need to call

AppManager.getInstance().someMethod();

所以,做所有的计算在里面。您可以保存当前活动的对象中的管理类,或者您可以抽象出功能完全脱离了活动,并能更好地控制您的code。是的,当然,你可以有一个以上的单班。我通常在我的项目来处理不同的任务,几乎是6-7辛格尔顿经理。

So do all your calculation in it. You can store the object of current activity in the Manager class or you can abstract out the functionality completely out of the Activity and can get better control over your code. And yes of course you can have more than one singleton classes. I normally have almost 6-7 Singleton managers in my project to handle different tasks.

这篇关于如何调用一个“方法”中的另一项活动定义上点击的小窗口按钮?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆