Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to get view reference from menu item?

Iam trying to get a menu item's reference but i just cant. This whole thing is inside a fragment.

Menu: boat_accept_menu.xml:

    <?xml version="1.0" encoding="utf-8"?>
    <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.example.toolbar.MainActivity" >

    <item
        android:id="@+id/done_boat_select"
        android:title="@string/done_C"
        app:showAsAction="always"/>

</menu>

You can see the comment inside the code, i cannot get the reference.

Code:

@Override
        public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
            getActivity().getMenuInflater().inflate(R.menu.boat_accept_menu, menu);


        //boatClassSelectedBtn =(View) menu.findItem(R.id.done_boat_select);
        //Cannot Cast Exception

        //boatClassSelectedBtn =(View) menu.findItem(R.id.done_boat_select).getActionView();
        //Null reference

        //boatClassSelectedBtn = menu.getItem(0).getActionView();
        //Null reference

        if (boatClassSelectedBtn == null) {
            Log.e("boatClassSelectedBtn", "NULL!");
        }
        else
        {
            Log.i("boatClassSelectedBtn", "OK!");
        }

    }

What is the problem? How to achieve this?

like image 231
Adam Varhegyi Avatar asked Nov 01 '22 07:11

Adam Varhegyi


2 Answers

This is the correct way to get the reference of a MenuItem:

private MenuItem boatClassSelectedButton;


@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.main, menu);
    boatClassSelectedButton = (MenuItem) menu.findItem(R.id.done_boat_select);
    return true;
}
like image 95
Jorgesys Avatar answered Nov 12 '22 14:11

Jorgesys


Ended up:

@Override
    public void onCreateOptionsMenu(final Menu menu, MenuInflater inflater) {
        getActivity().getMenuInflater().inflate(R.menu.boat_accept_menu, menu);

        MenuItem menuItem = menu.getItem(0);

        TextView doneTv = new TextView (getActivity());   
        doneTv.setTextView("Ok")

        boatClassSelectedBtn = menuItem.getActionView();

        boatClassSelectedBtn.setOnClickListener(this);

    }
like image 30
Adam Varhegyi Avatar answered Nov 12 '22 14:11

Adam Varhegyi