简体   繁体   English

从多个视图调用onCreateOptionsMenu()

[英]Calling onCreateOptionsMenu() from multiple views

This may be because of my lack of full understanding of how java works. 这可能是由于我对java的工作原理缺乏全面的了解。 Still learning! 还在学习!

Let's say we have an activity, with onCreate code. 假设我们有一个活动,其中包含onCreate代码。

public class GameActivity extends Activity {
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);

        setContentView(new GameMainView(this));
    }
}

We've got our view now. 我们现在有我们的看法。 My question is this. 我的问题是这个。 There are subroutines in both the GameActivity class and the GameMainView class that I want to call using the responses from onCreateOptionsMenu(). 我想使用onCreateOptionsMenu()的响应来调用GameActivity类和GameMainView类中的子例程。 How would I get access to both those classes? 我将如何访问这两个课程? I know that I could create an abstract class specifically for onCreateOptionsMenu() and have GameActivity and GameMainView override it to perform what they need. 我知道我可以创建一个专门用于onCreateOptionsMenu()的抽象类,并让GameActivity和GameMainView重写它来执行他们所需的操作。 Is this the only option? 这是唯一的选择吗? Does onCreateOptionsMenu() only get called once? 是否onCreateOptionsMenu()仅被调用一次? And if so, where? 如果是这样,在哪里? If I override it all over the place, will they all get executed? 如果我在所有地方都覆盖它,它们会全部执行吗?

If you write your Activity like this: 如果您这样编写活动:

public class GameActivity extends Activity {
    private GameMainView gameMainView;
    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        gameMainView = new GameMainView(this);
        setContentView(gameMainView);
    }
}

Then in your method which handles the selected menu option you can deal with the selection in the activity, and forward it on to the view too. 然后,在处理选定菜单选项的方法中,您可以处理活动中的选择,并将其转发到视图上。

You can only override it in your activity class. 您只能在活动类中覆盖它。 Keep a reference to GameMainView in the activity and call methods in the view when buttons are pressed. 按下按钮时,在活动中保留对GameMainView的引用,并在视图中调用方法。

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

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