简体   繁体   English

Android:从菜单项开始新的活动

[英]Android: Start a new activity from menu item

I'm Trying to open a second screen for my application. 我正在尝试为我的应用程序打开第二个屏幕。 The user have to click on a menu item and then the screen must open. 用户必须单击菜单项,然后必须打开屏幕。 But what i try it always just ignores the rule after the case statement. 但是,我尝试执行的操作始终只是忽略case语句后的规则。

    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
        case R.id.OpenScreen:  startActivity(new Intent(this, SecondScreenActivity.class));;
                            break;
    }
    return true;

I've also added the activity to AndroidManifest.xml inside the tag. 我还将该活动添加到标记内的AndroidManifest.xml中。

Any help will be apreciated 任何帮助将不胜感激


Solution

I had the finish() in the constructor of the new class. 我在新类的构造函数中使用了finish()

For me your java code is correct and work for me that way. 对我来说,您的Java代码是正确的,并且可以为我工作。

However when I learned Android, when I came at the point of starting a new activity I faced the same problem as you, nothing was happening, without any error, simply not working. 但是,当我学习Android时,刚开始进行一项新活动时,我遇到了与您相同的问题,什么也没有发生,没有任何错误,只是无法正常工作。

In my case I forgot to add the activity in the AndroidManifest.xml file. 就我而言,我忘记将活动添加到AndroidManifest.xml文件中。 Perhaps it is the same for you. 也许对您来说一样。

Your AndroidManifest file should contain somewhere something like that 您的AndroidManifest文件应包含类似的内容

<activity
    android:name=".SecondScreenActivity" >
</activity>

this tell the system that SecondScreenActivity exitst. 这告诉系统SecondScreenActivity退出。

In http://developer.android.com/guide/topics/manifest/activity-element.html they say : http://developer.android.com/guide/topics/manifest/activity-element.html中,他们说:

All activities must be represented by elements in the manifest file. 所有活动必须由清单文件中的元素表示。 Any that are not declared there will not be seen by the system and will never be run. 任何未声明的文件将不会被系统看到,也永远不会运行。

Hope this helps 希望这可以帮助

try like this 这样尝试

public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
    case R.id.OpenScreen:  
            startActivity(new Intent(YourClass.this, SecondScreenActivity.class));
                           break;
}
return true;

Don't return true for onOptionsItemSelected . 不要为onOptionsItemSelected return true

call super method like this. 调用这样的超级方法。

return super.onOptionsItemSelected(item);

instead of return true; 而不是返回true;

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

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