How to get view reference from menu item?

2020-07-22 18:58发布

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?

4条回答
够拽才男人
2楼-- · 2020-07-22 19:12

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;
}
查看更多
相关推荐>>
3楼-- · 2020-07-22 19:16
@Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
    super.onCreateOptionsMenu(menu, inflater);
    inflater.inflate(R.menu.menu_manage_clubs, menu);

    MenuItem deleteItem = menu.findItem(R.id.action_delete_club);
    if (!canDelete()) {
        deleteItem.setVisible(false);
    }
}
查看更多
Juvenile、少年°
4楼-- · 2020-07-22 19:25

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

    }
查看更多
地球回转人心会变
5楼-- · 2020-07-22 19:30

Try this.

MenuItem boatClassSelectedBtn = menu.findItem(R.id.done_boat_select);
查看更多
登录 后发表回答