user3376241
user3376241

Reputation: 37

Android menu not recognizing onClick in xml file

Here is my xml file (res/menu/main.xml):

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    android:onClick="onClickMenu"
    app:showAsAction="never"/>

and the following is in my main activity class:

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

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    // Handle action bar item clicks here. The action bar will
    // automatically handle clicks on the Home/Up button, so long
    // as you specify a parent activity in AndroidManifest.xml.
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        return true;
    }
    return super.onOptionsItemSelected(item);
}


public void onClickMenu(MenuItem item){
    disp.setText("TextVisibleAfterClick");
    
}

Why is it that my code keeps throwing the following error?!:

android.view.InflateException: Couldn't resolve menu item onClick handler onClickMenu in class android.view.ContextThemeWrapper

I'm not understanding because I am accepting a MenuItem in my method and the XML paramater for onClick is the exact same!

------ edit: entire XML -----

<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.beej.app.MainActivity" >

<item
    android:id="@+id/action_settings"
    android:orderInCategory="100"
    android:title="@string/action_settings"
    android:onClick="onClickMenu"
    app:showAsAction="never"/>

</menu>

Upvotes: 2

Views: 671

Answers (2)

MilanNz
MilanNz

Reputation: 1341

Try this:

public boolean onOptionsItemSelected(MenuItem item) {
    // Handle presses on the action bar items
    switch (item.getItemId()) {
        case R.id.action_settings:
            disp.setText("TextVisibleAfterClick"); //or something else
            return true;
        default:
            return super.onOptionsItemSelected(item);
    }
}

Upvotes: 2

Jo&#227;o Menighin
Jo&#227;o Menighin

Reputation: 3225

Try this:

public void onClickMenu(View v) {
    MenuItem item = (MenuItem) v; // If you need it
    disp.setText("TextVisibleAfterClick");
}

Upvotes: -1

Related Questions