简体   繁体   中英

Android: Change actionbar icon after click and change it back after onCreate()

I try to change the icon of the action bar to a progress bar in onOptionsItemSelected(MenuItem) method.

    public boolean onOptionsItemSelected(MenuItem item) {
    switch (item.getItemId()) {
    case android.R.id.home:
        NavUtils.navigateUpFromSameTask(this);
        return true;
    case R.id.progressitem2:
        mProgress = item;
        mProgressCreate = mProgress;
        mProgress.setActionView(R.layout.progress);
        mLayout.removeView(mTable);
        // Execute code that change mTable again.
        return true;
    }

progress.xml file:

<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
              android:layout_width="wrap_content"
              android:layout_height="wrap_content"
              android:addStatesFromChildren="true"
              android:focusable="true"
              android:paddingLeft="4dp"
              android:paddingRight="4dp"
              android:gravity="center" >
    <ProgressBar
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:focusable="true"
            style="@android:style/Widget.ProgressBar.Small"/>

</LinearLayout> 

The action bar is created in this way:

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.actionbar, menu);
    mProgress = menu.getItem(0);
    mProgressCreate = mProgress;
    return true;
}

action_menu.xml

<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android">
        <item android:id="@+id/progressitem2" 
            android:icon="@drawable/ic_action_refresh"
            android:title="Reload"
            android:showAsAction="ifRoom|withText"
            android:visible="true" />
</menu>

This works good. The progress icon is shown after I click the action bar icon.

I try to keep the reference of the original action bar symbol in mProgressCreate and try to add the action view back at the end of the onCreate() method:

mProgress.setActionView(mProgressCreate.getActionView());

But this do not work...

What`s wrong here?

Regards, Sandro

I found the solution. I simply forgot to call invalidateOptionsMenu() before I reset the action view with mProgress.setActionView(mProgressCreate.getActionView());

invalidateOptionsMenu();
mProgress.setActionView(mProgressCreate.getActionView());

And everything is working fine :-).

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