通过不同的类调用活动类的函数

时间:2014-08-05 19:23:31

标签: java android

我想调用属于某个活动类的函数,并使用来自不同类的资源。

我该怎么做?我尝试将object作为活动类的context (this)that doesn't work

那么我可以通过什么方式实现这一目标呢?


我通过这个将protected void onCreate(final Bundle savedInstanceState) { super.onCreate(savedInstanceState); getWindow().requestFeature(Window.FEATURE_ACTION_BAR); getActionBar().hide(); setContentView(R.layout.main_view); mainAppContext = this; Main mainObj=new Main(); gMapObj.initiateMap(mainAppContext,mainObj, mapFrag); //Control shifted to other class. } 主类传递给了其他类。但是我如何使用它呢?

{{1}}

1 个答案:

答案 0 :(得分:0)

我不确定我的问题是否正确,但据我所知,这是我的建议。

您不应该创建对象。您想要在实例化的活动上调用方法。创建对象时,您将失去与活动的所有连接。

您可以制作方法static,然后调用它。

如果您的活动是MainActivity,请在此活动中创建public static void someMethod()并从其他类调用MainActivity.someMethod()

如果您能够传递引用,请执行此操作,将上下文作为参数传递。

修改

这就是你应该做的事情:

public class SecondClass extends Activity {
    protected Context context;

    public SecondClass(Context context){
        this.context = context;
    }

    protected void onCreate(final Bundle savedInstanceState) {

        super.onCreate(savedInstanceState);
        getWindow().requestFeature(Window.FEATURE_ACTION_BAR);
        getActionBar().hide();
        setContentView(R.layout.main_view);

        context.initiateMap(mainAppContext,mainObj, mapFrag);

    }

}

在您的活动中执行此操作

new SecondClass(this);