[英]How to call a function of one activity from another activity without creating new object of the activity being called?
I created activity1
and called activity2
from the activity1
.Now i wish to call function of activity1
staying at activity2
and "without initializing instant of activity1
" in order to avoid recreated of activity 1
again.I want to know the code in callfirst()
of my second activity 我创建
activity1
,并呼吁activity2
从activity1
。现在我想调用的功能activity1
停留在activity2
和“没有初始化的即时activity1
,以”为了避免重建的activity 1
again.I想知道的代码callfirst()
的我的第二项活动
here is my mainactivity 这是我的主要活动
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.Main);
Button button1 = FindViewById<Button> (Resource.Id.myButton1);
button1.Click += (object sender, EventArgs e) => firstload ();
}
protected override void OnSaveInstanceState (Bundle outState)
{
base.OnSaveInstanceState (outState);
}
public void firstload()
{
StartActivity(typeof(first));
}
here is my first activity 这是我的第一次活动
public class first : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.first);
Button btn = FindViewById<Button>(Resource.Id.btnfirst);
btn.Click += (object sender, EventArgs e) => loadsecond();
}
public void loadsecond()
{
StartActivity (typeof(second));
}
public void message()
{
Toast.MakeText (this, "fxn of activityfirst called from activitysecond", ToastLength.Short).Show ();
}
}
here is my second activity 这是我的第二项活动
public class second : Activity
{
protected override void OnCreate (Bundle bundle)
{
base.OnCreate (bundle);
SetContentView (Resource.Layout.second);
Button btn = FindViewById<Button> (Resource.Id.btnsecond);
btn.Click += (object sender, EventArgs e) => callfirst();
}
public void callfirst()
{
//what should i do here ???
}
} }
if you need to use some common functions and global variables, better create a class that holds them - like Globals.java
. 如果需要使用一些通用函数和全局变量,则最好创建一个包含它们的类
Globals.java
。 There you can have your global variables: 在那里,您可以拥有全局变量:
public static String someGlobalString = "";
public static void someGlobalFunction(){ };
and you can call them from your code like: 您可以从您的代码中调用它们,例如:
Globals.someGlobalString = "some value";
Globals.someGlobalFunction();
创建该方法static并使用该类名本身进行调用,因为static方法和变量从该类名本身进行调用
aYou can indeed use static methods for this purpose, but you should not use activities for static methods to be used by other activities. a您确实可以为此目的使用静态方法,但您不应将活动用于其他活动要使用的静态方法。 That is not how they are supposed to work.
那不是他们应该如何工作的。 They should be separate entities which can pass messages to each other using the Binder framework.
它们应该是可以使用Binder框架相互传递消息的单独实体。 If you do need to have access to the same method, then simply create another class which has that static method available to both activities.
如果确实需要访问同一方法,则只需创建另一个类,该类的两个方法都可以使用该静态方法。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.