Android 我想从抽屉按钮调用MainActivity的函数

Android 我想从抽屉按钮调用MainActivity的函数,android,model-view-controller,kotlin,navigation-drawer,Android,Model View Controller,Kotlin,Navigation Drawer,是否可以从抽屉中调用活动函数 假设:主活动已打开。其中有一个函数displayImage()。我想从抽屉里调用它。**请查看下面的代码片段** **Please go through the bellow code snippet** drawer.xml file <?xml version="1.0" encoding="utf-8"?> <menu xmlns:android="http://schemas.android.com/apk/res/android"

是否可以从抽屉中调用活动函数

假设:主活动已打开。其中有一个函数displayImage()。我想从抽屉里调用它。

**请查看下面的代码片段**
**Please go through the bellow code snippet**
drawer.xml file
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:tools="http://schemas.android.com/tools"
    tools:showIn="navigation_view">

    <group android:checkableBehavior="single">
        <item
            android:id="@+id/u_name"
            android:icon="@drawable/lead_leader"
            android:title="User name" />

        <item
            android:id="@+id/logout"
            android:icon="@drawable/logout"
            android:title="Logout" />

    </group>
</menu>
**after that add bellow code in  your Mainactivity.java file**

 @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        // Inflate the menu; this adds items to the action bar if it is present.
        getMenuInflater().inflate(R.menu.lead_profile, menu);
        return true;
    }

    @Override
    public boolean onOptionsItemSelected(MenuItem item) {

        int id = item.getItemId();
        if (id == R.id.logout) {

            //call your other method according navigation drawer item with other id in a different if block.

 ///call your function here
        }

        return super.onOptionsItemSelected(item);
    }
drawer.xml文件 **然后在Mainactivity.java文件中添加以下代码** @凌驾 公共布尔onCreateOptions菜单(菜单){ //为菜单充气;这会将项目添加到操作栏(如果存在)。 getMenuInflater().充气(R.menu.lead_profile,menu); 返回true; } @凌驾 公共布尔值onOptionsItemSelected(菜单项项){ int id=item.getItemId(); if(id==R.id.logout){ //根据不同if块中具有其他id的导航抽屉项调用其他方法。 ///在这里调用你的函数 } 返回super.onOptionsItemSelected(项目); }
将该函数设置为公共静态。可以通过执行MainActivity.displayImage()调用它@Droidv那是个可怕的主意。如果它实际上不需要活动成员变量,则它不应位于MainActivity上。如果是这样,则不能使用staticdisplayImage()正在使用MainActivity的上下文它将在导航抽屉菜单中添加一个项目,当您单击该项目时,所需的函数将是call plz。如果您遇到任何问题,请告诉我是否在菜单选项上未调用OnCreateOptions菜单(),但在导航抽屉上未调用。我要了一个从左边来的抽屉,用来盖活动