简体   繁体   中英

Dynamically change toolbar layout in fragment

So I created menu_event.xml to customize the toolbar layout of my fragment like this:

<item android:id="@+id/action_add"
    android:icon="@drawable/ic_action_new"
    android:title="@string/action_settings"
    android:showAsAction="ifRoom"
    tools:ignore="AppCompatResource" />

<item android:id="@+id/action_search"
    android:icon="@drawable/search_icon"
    android:title="@string/action_search"
    android:showAsAction="ifRoom"
    tools:ignore="AppCompatResource" />

In order to do it, I used the onCreateOptionsMenu() method in my class and I also set setHasOptionsMenu(true) in my onCreateView() method:

public class ListEventActivity extends Fragment {

    public ListEventActivity() {
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
    }

    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        setHasOptionsMenu(true);
        return inflater.inflate(R.layout.activity_list_event, container, false);
    }

    @Override
    public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
        inflater.inflate(R.menu.menu_event, menu);
        super.onCreateOptionsMenu(menu, inflater);
    }
}

But even this way it doesn't change the toolbar layout and the action overflow item remains (instead it adds "settings" and "search" to its items...

Any ideas about how to solve it?

您可以使用invalidateOptionsMenu (或在使用AppCompat的情况下为supportInvalidateOptionsMenu )方法刷新ActionBar。

Just add a regular XML layout file and use findViewById to find the view and manipulate it to your heart's desire. You can then set your click handlers etc to handle button click

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM