简体   繁体   English

如何在Android中通过其他活动调用方法

[英]How to call a method from a different activity in Android

I have an app that creates a display of buttons dynamically using this method 我有一个应用程序使用此方法动态创建按钮显示

public void ButtonLayout() { 
    //Creates new layout and params to go with
    final LinearLayout llb = (LinearLayout)findViewById(R.id.buttonlayout);


    //Creates new buttons and indexes
    for(int i = 0; i < count; i++) {
        Button displayButton = buttonlist.get(i);
        //Adds button to view with index and parameters
        if(displayButton.getTag() == tag || tag == null){
            llb.addView(displayButton, i, lp);
        }
    }
}

it then opens up a new activity which is a menu, The menu has buttons on it, I want to be able to recall the above method (reload all the buttons) from my menu activity, I cant just start the first activity again. 然后它打开一个新的活动,它是一个菜单,该菜单上有按钮,我希望能够从我的菜单活动中调用上述方法(重新加载所有按钮),我无法再次开始第一个活动。

Is there a way of doing this? 有办法吗?

I would write class or method where you inject the dependency to a activity and handle your work there 我会编写类或方法,在其中将依赖项注入到活动中并在那里处理您的工作

for example: 例如:

public class Util{    
pulic static void  doSomething(LinearLayout  llb, List<Buttons> buttonlist){
    llb.clear(); // pseudocode
    for(int i = 0; i < count; i++) {
        Button displayButton = buttonlist.get(i);
        //Adds button to view with index and parameters
        if(displayButton.getTag() == tag || tag == null){
            llb.addView(displayButton, i, lp);
        }
    }
}

You can write a Parent activity, which would have this method. 您可以编写具有此方法的Parent活动。 The other activities that need to use this method, can extend this parent activity, and can re-use the layout code that you have here. 需要使用此方法的其他活动可以扩展此父活动,并可以重新使用此处的布局代码。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM