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

时间:2018-09-07 13:58:10

标签: android model-view-controller kotlin navigation-drawer

是否可以从抽屉中调用Activity函数?

说:打开主活动。其中有一个函数displayImage()。我想从抽屉里叫它。

1 个答案:

答案 0 :(得分:0)

**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);
    }