简体   繁体   English

菜单项开放活动

[英]Menu items opening activities

I have a menu on every activity besides my login screen of my app and I want the items to take me to each of their respective activities.除了我的应用程序的登录屏幕之外,我的每个活动都有一个菜单,我希望这些项目将我带到他们各自的每个活动。 All of the tutorials I see only display toast messages.我看到的所有教程都只显示吐司消息。 I have one menu item working but am unsure of how I can add the rest.我有一个菜单项工作,但不确定如何添加 rest。

this is from my activity.java file, it works, but I want to add the other buttons in line with this as well so that I can just copy and paste to my other activities.这是来自我的活动。java 文件,它可以工作,但我想添加与此一致的其他按钮,以便我可以复制并粘贴到我的其他活动中。

 @Override
public boolean onOptionsItemSelected(MenuItem item) {
    if (item.getItemId() == R.id.menu_home) {
        Intent i = new Intent(this, activityHome.class);
        this.startActivity(i);
        return true;
    }
    return super.onOptionsItemSelected(item);

}

You have different options:你有不同的选择:

  • Use a single Activity with different Fragment s (and you can use the Navigation component )使用具有不同Fragment的单个Activity (并且您可以使用Navigation 组件
  • Use an abstract BaseActivity with the common code使用带有通用代码的抽象BaseActivity
  • Create an util method to handle the common code in the onOptionsItemSelected method.创建一个 util 方法来处理onOptionsItemSelected方法中的公共代码。

Option with an BaseActivity :带有BaseActivity的选项:

public abstract class BaseActivity extends AppCompatActivity {

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(getLayoutId());
    }

    protected abstract @LayoutRes int getLayoutId();

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        switch (item.getItemId()){
            case R.id.search:
                //...
                return true;
            //...   
                 
        }
        return super.onOptionsItemSelected(item);
    }
}

And then in each Activity :然后在每个Activity中:

public class ChildActivity extends BaseActivity {
    @Override
    protected int getLayoutId() {
        return R.layout.activity_main;
    }

    @Override
    public boolean onOptionsItemSelected(@NonNull MenuItem item) {
        if (item.getItemId() == ... ){
            //Do something
        }
        return super.onOptionsItemSelected(item);
    }
}

Option with a util method:带有 util 方法的选项:

public static boolean utilOptionsItemSelected(@NonNull MenuItem item){
    switch (item.getItemId()){
        case R.id.search:
            //...
            return true;
        ///
    }
}

and in your在你的

public boolean onOptionsItemSelected(@NonNull MenuItem item) {
       if (item.getItemId() == ... ){
                //Do something
       }
       return Util.utilOptionsItemSelected(item);
}

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

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