gpt4 book ai didi

android - 如何将 Activity 实例传递给另一个 Activity

转载 作者:行者123 更新时间:2023-11-29 15:18:23 25 4
gpt4 key购买 nike

您好,我有一个名为 BaseActivity 的 Activity ,它扩展了 Activity。从这里我必须去 SettingsActivity 它扩展了 PreferenceActivity,按下菜单按钮。要启动一个位于独立类中的 AsyncTask,我需要一个 BaseActivity 实例。如何在 SettingsActivity 中获取 BaseActivity 实例?

有没有办法,例如:

intent.putExtra("activity_instance",BaseActivity.this);

最佳答案

使用 getter 和 setter 并将它们所在的类作为单例类。

这是一个单例类。使用这个类,我们可以在整个类中共享数据(例如:int、boolean、activity 实例...等)

public class CommonModelClass 
{
public static CommonModelClass singletonObject;
/** A private Constructor prevents any other class from instantiating. */

private Activity baseActivity;

public CommonModelClass()
{
// Optional Code
}
public static synchronized CommonModelClass getSingletonObject()
{
if (singletonObject == null)
{
singletonObject = new CommonModelClass();
}
return singletonObject;
}


/**
* used to clear CommonModelClass(SingletonClass) Memory
*/
public void clear()
{
singletonObject = null;
}


public Object clone() throws CloneNotSupportedException
{
throw new CloneNotSupportedException();
}

//getters and setters starts from here.it is used to set and get a value

public Activity getbaseActivity()
{
return baseActivity;
}

public void setbaseActivity(Activity baseActivity)
{
this.baseActivity = baseActivity;
}

}

在 BaseActivity 类中这样做。

         Class BaseActivity extends Activity{


@Override
protected void onCreate(Bundle savedInstanceState) {

CommonModelClass commonModelClass = CommonModelClass.getSingletonObject();

commonModelClass.setbaseActivity(BaseActivity.this);

//after using the BaseActivity instance dont forget to call commonModelClass.clear(); else it wont be garbage collected


}

}

在 SettingsActivity 中这样做

 Class SettingsActivity extends Activity{

@Override
protected void onCreate(Bundle savedInstanceState) {
CommonModelClass commonModelClass = CommonModelClass.getSingletonObject();



Activity instanceBaseActivity= commonModelClass.getbaseActivity();;


}

}

如果可行,请打勾

关于android - 如何将 Activity 实例传递给另一个 Activity,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/21772794/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com