Example usage for android.view MenuItem setActionView

List of usage examples for android.view MenuItem setActionView

Introduction

In this page you can find the example usage for android.view MenuItem setActionView.

Prototype

public MenuItem setActionView(@LayoutRes int resId);

Source Link

Document

Set an action view for this menu item.

Usage

From source file:com.nextgis.mobile.activity.MainActivity.java

public synchronized void onRefresh(boolean isRefresh) {
    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
        MenuItem refreshItem = mToolbar.getMenu().findItem(R.id.menu_refresh);
        if (null != refreshItem) {
            if (isRefresh) {
                if (refreshItem.getActionView() == null) {
                    refreshItem.setActionView(R.layout.layout_refresh);
                    ProgressBar progress = (ProgressBar) refreshItem.getActionView()
                            .findViewById(R.id.refreshingProgress);
                    if (progress != null)
                        progress.getIndeterminateDrawable().setColorFilter(
                                ContextCompat.getColor(this, R.color.color_grey_200), PorterDuff.Mode.SRC_IN);
                }/*from w  w w.j  a  v a  2s. c  o  m*/
            } else
                stopRefresh(refreshItem);
        }
    }
}

From source file:at.ac.tuwien.detlef.activities.MainActivity.java

private void setRefreshBtnView(int id) {
    if (menu == null) {
        return;//from  w w w.  j  a  v  a 2 s .c  o  m
    }

    MenuItem refreshBtn = menu.findItem(R.id.refresh);

    if (refreshBtn == null) {
        return;
    }

    refreshBtn.setActionView(id);
    refreshBtn.getActionView().setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            onRefreshPressed();
        }
    });
}

From source file:net.ustyugov.jtalk.activity.XMLConsole.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    MenuInflater inflater = getMenuInflater();
    inflater.inflate(R.menu.xml, menu);//ww w  .  j  a va 2  s  .  com

    MenuItem.OnActionExpandListener listener = new MenuItem.OnActionExpandListener() {
        @Override
        public boolean onMenuItemActionCollapse(MenuItem item) {
            searchString = "";
            updateList();
            return true;
        }

        @Override
        public boolean onMenuItemActionExpand(MenuItem item) {
            return true;
        }
    };

    SearchView searchView = new SearchView(this);
    searchView.setQueryHint(getString(android.R.string.search_go));
    searchView.setSubmitButtonEnabled(true);
    searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
        @Override
        public boolean onQueryTextChange(String newText) {
            return false;
        }

        @Override
        public boolean onQueryTextSubmit(String query) {
            searchString = query;
            updateList();
            return true;
        }
    });

    MenuItem item = menu.findItem(R.id.search);
    item.setActionView(searchView);
    item.setShowAsAction(MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
    item.setOnActionExpandListener(listener);
    return super.onCreateOptionsMenu(menu);
}

From source file:com.nextgis.mobile.activity.MainActivity.java

protected void stopRefresh(final MenuItem refreshItem) {
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.HONEYCOMB)
        return;/*ww  w .  ja  v a2  s .co m*/

    Handler handler = new Handler(Looper.getMainLooper());
    final Runnable r = new Runnable() {
        @TargetApi(Build.VERSION_CODES.HONEYCOMB)
        public void run() {
            if (refreshItem != null && refreshItem.getActionView() != null) {
                refreshItem.getActionView().clearAnimation();
                refreshItem.setActionView(null);
            }
        }
    };
    handler.post(r);
}

From source file:net.bluecarrot.lite.MainActivity.java

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

    // setup the sharedPreferences
    savedPreferences = PreferenceManager.getDefaultSharedPreferences(this);

    // if the app is being launched for the first time
    if (savedPreferences.getBoolean("first_run", true)) {
        //todo presentation
        // save the fact that the app has been started at least once
        savedPreferences.edit().putBoolean("first_run", false).apply();
    }/* w  w  w . ja  v a  2 s. c  o m*/

    setContentView(R.layout.activity_main);//load the layout

    //**MOBFOX***//

    banner = (Banner) findViewById(R.id.banner);
    final Activity self = this;

    banner.setListener(new BannerListener() {
        @Override
        public void onBannerError(View view, Exception e) {
            //Toast.makeText(self, e.getMessage(), Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerLoaded(View view) {
            //Toast.makeText(self, "banner loaded", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClosed(View view) {
            //Toast.makeText(self, "banner closed", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerFinished(View view) {
            // Toast.makeText(self, "banner finished", Toast.LENGTH_SHORT).show();
        }

        @Override
        public void onBannerClicked(View view) {
            //Toast.makeText(self, "banner clicked", Toast.LENGTH_SHORT).show();
        }

        @Override
        public boolean onCustomEvent(JSONArray jsonArray) {
            return false;
        }
    });

    banner.setInventoryHash(appHash);
    banner.load();

    // setup the refresh layout
    swipeRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.swipe_container);
    swipeRefreshLayout.setColorSchemeResources(R.color.officialBlueFacebook, R.color.darkBlueSlimFacebookTheme);// set the colors
    swipeRefreshLayout.setOnRefreshListener(new SwipeRefreshLayout.OnRefreshListener() {
        @Override
        public void onRefresh() {
            refreshPage();//reload the page
            swipeRefresh = true;
        }
    });

    /** get a subject and text and check if this is a link trying to be shared */
    String sharedSubject = getIntent().getStringExtra(Intent.EXTRA_SUBJECT);
    String sharedUrl = getIntent().getStringExtra(Intent.EXTRA_TEXT);

    // if we have a valid URL that was shared by us, open the sharer
    if (sharedUrl != null) {
        if (!sharedUrl.equals("")) {
            // check if the URL being shared is a proper web URL
            if (!sharedUrl.startsWith("http://") || !sharedUrl.startsWith("https://")) {
                // if it's not, let's see if it includes an URL in it (prefixed with a message)
                int startUrlIndex = sharedUrl.indexOf("http:");
                if (startUrlIndex > 0) {
                    // seems like it's prefixed with a message, let's trim the start and get the URL only
                    sharedUrl = sharedUrl.substring(startUrlIndex);
                }
            }
            // final step, set the proper Sharer...
            urlSharer = String.format("https://m.facebook.com/sharer.php?u=%s&t=%s", sharedUrl, sharedSubject);
            // ... and parse it just in case
            urlSharer = Uri.parse(urlSharer).toString();
            isSharer = true;
        }
    }

    // setup the webView
    webViewFacebook = (WebView) findViewById(R.id.webView);
    setUpWebViewDefaults(webViewFacebook);
    //fits images to screen

    if (isSharer) {//if is a share request
        webViewFacebook.loadUrl(urlSharer);//load the sharer url
        isSharer = false;
    } else
        goHome();//load homepage

    //        webViewFacebook.setOnTouchListener(new OnSwipeTouchListener(getApplicationContext()) {
    //            public void onSwipeLeft() {
    //                webViewFacebook.loadUrl("javascript:try{document.querySelector('#messages_jewel > a').click();}catch(e){window.location.href='" +
    //                        getString(R.string.urlFacebookMobile) + "messages/';}");
    //            }
    //
    //        });

    //WebViewClient that is the client callback.
    webViewFacebook.setWebViewClient(new WebViewClient() {//advanced set up

        // when there isn't a connetion
        public void onReceivedError(WebView view, int errorCode, String description, String failingUrl) {
            String summary = "<h1 style='text-align:center; padding-top:15%; font-size:70px;'>"
                    + getString(R.string.titleNoConnection) + "</h1> <h3 "
                    + "style='text-align:center; padding-top:1%; font-style: italic;font-size:50px;'>"
                    + getString(R.string.descriptionNoConnection)
                    + "</h3>  <h5 style='font-size:30px; text-align:center; padding-top:80%; "
                    + "opacity: 0.3;'>" + getString(R.string.awards) + "</h5>";
            webViewFacebook.loadData(summary, "text/html; charset=utf-8", "utf-8");//load a custom html page

            noConnectionError = true;
            swipeRefreshLayout.setRefreshing(false); //when the page is loaded, stop the refreshing
        }

        // when I click in a external link
        public boolean shouldOverrideUrlLoading(WebView view, String url) {
            if (url == null || Uri.parse(url).getHost().endsWith("facebook.com")
                    || Uri.parse(url).getHost().endsWith("m.facebook.com") || url.contains(".gif")) {
                //url is ok
                return false;
            } else {
                if (Uri.parse(url).getHost().endsWith("fbcdn.net")) {
                    //TODO add the possibility to download and share directly

                    Toast.makeText(getApplicationContext(), getString(R.string.downloadOrShareWithBrowser),
                            Toast.LENGTH_LONG).show();
                    //TODO get bitmap from url

                    Intent intent = new Intent(Intent.ACTION_VIEW, Uri.parse(url));
                    startActivity(intent);
                    return true;
                }

                //if the link doesn't contain 'facebook.com', open it using the browser
                startActivity(new Intent(Intent.ACTION_VIEW, Uri.parse(url)));
                return true;
            } //https://www.facebook.com/dialog/return/close?#_=_
        }

        //START management of loading
        @Override
        public void onPageStarted(WebView view, String url, Bitmap favicon) {
            //TODO when I push on messages, open messanger
            //                if(url!=null){
            //                    if (url.contains("soft=messages") || url.contains("facebook.com/messages")) {
            //                        Toast.makeText(getApplicationContext(),"Open Messanger",
            //                                Toast.LENGTH_SHORT).show();
            //                        startActivity(new Intent(getPackageManager().getLaunchIntentForPackage("com.facebook.orca")));//messanger
            //                    }
            //                }

            // show you progress image
            if (!swipeRefresh) {
                if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                    final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                    refreshItem.setActionView(R.layout.circular_progress_bar);
                }
            }
            swipeRefresh = false;
            super.onPageStarted(view, url, favicon);
        }

        @Override
        public void onPageFinished(WebView view, String url) {
            if (optionsMenu != null) {//TODO fix this. Sometimes it is null and I don't know why
                final MenuItem refreshItem = optionsMenu.findItem(R.id.refresh);
                refreshItem.setActionView(null);
            }

            //load the css customizations
            String css = "";
            if (savedPreferences.getBoolean("pref_blackTheme", false)) {
                css += getString(R.string.blackCss);
            }
            if (savedPreferences.getBoolean("pref_fixedBar", true)) {

                css += getString(R.string.fixedBar);//get the first part

                int navbar = 0;//default value
                int resourceId = getResources().getIdentifier("status_bar_height", "dimen", "android");//get id
                if (resourceId > 0) {//if there is
                    navbar = getResources().getDimensionPixelSize(resourceId);//get the dimension
                }
                float density = getResources().getDisplayMetrics().density;
                int barHeight = (int) ((getResources().getDisplayMetrics().heightPixels - navbar - 44)
                        / density);

                css += ".flyout { max-height:" + barHeight + "px; overflow-y:scroll;  }";//without this doen-t scroll

            }
            if (savedPreferences.getBoolean("pref_hideSponsoredPosts", false)) {
                css += getString(R.string.hideSponsoredPost);
            }

            //apply the customizations
            webViewFacebook.loadUrl(
                    "javascript:function addStyleString(str) { var node = document.createElement('style'); node.innerHTML = "
                            + "str; document.body.appendChild(node); } addStyleString('" + css + "');");

            //finish the load
            super.onPageFinished(view, url);

            //when the page is loaded, stop the refreshing
            swipeRefreshLayout.setRefreshing(false);
        }
        //END management of loading

    });

    //WebChromeClient for handling all chrome functions.
    webViewFacebook.setWebChromeClient(new WebChromeClient() {
        //to the Geolocation
        public void onGeolocationPermissionsShowPrompt(String origin,
                GeolocationPermissions.Callback callback) {
            callback.invoke(origin, true, false);
            //todo notify when the gps is used
        }

        //to upload files
        //!!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
        // for >= Lollipop, all in one
        public boolean onShowFileChooser(WebView webView, ValueCallback<Uri[]> filePathCallback,
                FileChooserParams fileChooserParams) {

            /** Request permission for external storage access.
             *  If granted it's awesome and go on,
             *  otherwise just stop here and leave the method.
             */
            if (mFilePathCallback != null) {
                mFilePathCallback.onReceiveValue(null);
            }
            mFilePathCallback = filePathCallback;

            Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
            if (takePictureIntent.resolveActivity(getPackageManager()) != null) {

                // create the file where the photo should go
                File photoFile = null;
                try {
                    photoFile = createImageFile();
                    takePictureIntent.putExtra("PhotoPath", mCameraPhotoPath);
                } catch (IOException ex) {
                    // Error occurred while creating the File
                    Toast.makeText(getApplicationContext(), "Error occurred while creating the File",
                            Toast.LENGTH_LONG).show();
                }

                // continue only if the file was successfully created
                if (photoFile != null) {
                    mCameraPhotoPath = "file:" + photoFile.getAbsolutePath();
                    takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT, Uri.fromFile(photoFile));
                } else {
                    takePictureIntent = null;
                }
            }

            Intent contentSelectionIntent = new Intent(Intent.ACTION_GET_CONTENT);
            contentSelectionIntent.addCategory(Intent.CATEGORY_OPENABLE);
            contentSelectionIntent.setType("image/*");

            Intent[] intentArray;
            if (takePictureIntent != null) {
                intentArray = new Intent[] { takePictureIntent };
            } else {
                intentArray = new Intent[0];
            }

            Intent chooserIntent = new Intent(Intent.ACTION_CHOOSER);
            chooserIntent.putExtra(Intent.EXTRA_INTENT, contentSelectionIntent);
            chooserIntent.putExtra(Intent.EXTRA_TITLE, getString(R.string.chooseAnImage));
            chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, intentArray);

            startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);

            return true;
        }

        // creating image files (Lollipop only)
        private File createImageFile() throws IOException {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            File imageStorageDir = new File(
                    Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                    appDirectoryName);

            if (!imageStorageDir.exists()) {
                //noinspection ResultOfMethodCallIgnored
                imageStorageDir.mkdirs();
            }

            // create an image file name
            imageStorageDir = new File(imageStorageDir + File.separator + "IMG_"
                    + String.valueOf(System.currentTimeMillis()) + ".jpg");
            return imageStorageDir;
        }

        // openFileChooser for Android 3.0+
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType) {
            String appDirectoryName = getString(R.string.app_name).replace(" ", "");
            mUploadMessage = uploadMsg;

            try {
                File imageStorageDir = new File(
                        Environment.getExternalStoragePublicDirectory(Environment.DIRECTORY_PICTURES),
                        appDirectoryName);

                if (!imageStorageDir.exists()) {
                    //noinspection ResultOfMethodCallIgnored
                    imageStorageDir.mkdirs();
                }

                File file = new File(imageStorageDir + File.separator + "IMG_"
                        + String.valueOf(System.currentTimeMillis()) + ".jpg");

                mCapturedImageURI = Uri.fromFile(file); // save to the private variable

                final Intent captureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                captureIntent.putExtra(MediaStore.EXTRA_OUTPUT, mCapturedImageURI);
                //captureIntent.putExtra(MediaStore.EXTRA_SCREEN_ORIENTATION, ActivityInfo.SCREEN_ORIENTATION_PORTRAIT);

                Intent i = new Intent(Intent.ACTION_GET_CONTENT);
                i.addCategory(Intent.CATEGORY_OPENABLE);
                i.setType("image/*");

                Intent chooserIntent = Intent.createChooser(i, getString(R.string.chooseAnImage));
                chooserIntent.putExtra(Intent.EXTRA_INITIAL_INTENTS, new Parcelable[] { captureIntent });

                startActivityForResult(chooserIntent, FILECHOOSER_RESULTCODE);
            } catch (Exception e) {
                Toast.makeText(getApplicationContext(), ("Camera Exception"), Toast.LENGTH_LONG).show();
            }
        }

        // openFileChooser for other Android versions

        /**
         * may not work on KitKat due to lack of implementation of openFileChooser() or onShowFileChooser()
         * https://code.google.com/p/android/issues/detail?id=62220
         * however newer versions of KitKat fixed it on some devices
         */
        public void openFileChooser(ValueCallback<Uri> uploadMsg, String acceptType, String capture) {
            openFileChooser(uploadMsg, acceptType);
        }

    });

    // OnLongClickListener for detecting long clicks on links and images
    // !!!!!!!!!!! thanks to FaceSlim !!!!!!!!!!!!!!!
    webViewFacebook.setOnLongClickListener(new View.OnLongClickListener() {
        @Override
        public boolean onLongClick(View v) {
            // activate long clicks on links and image links according to settings
            if (true) {
                WebView.HitTestResult result = webViewFacebook.getHitTestResult();
                if (result.getType() == WebView.HitTestResult.SRC_ANCHOR_TYPE
                        || result.getType() == WebView.HitTestResult.SRC_IMAGE_ANCHOR_TYPE) {
                    Message msg = linkHandler.obtainMessage();
                    webViewFacebook.requestFocusNodeHref(msg);
                    return true;
                }
            }
            return false;
        }
    });
    // ATTENTION: This was auto-generated to implement the App Indexing API.
    // See https://g.co/AppIndexing/AndroidStudio for more information.
    client = new GoogleApiClient.Builder(this).addApi(AppIndex.API).build();
}

From source file:org.wikipedia.edit.EditSectionActivity.java

@Override
public boolean onCreateOptionsMenu(Menu menu) {
    getMenuInflater().inflate(R.menu.menu_edit_section, menu);
    MenuItem item = menu.findItem(R.id.menu_save_section);

    if (editSummaryFragment.isActive()) {
        item.setTitle(getString(R.string.edit_next));
    } else if (editPreviewFragment.isActive()) {
        item.setTitle(getString(R.string.edit_done));
    } else {/*from w  w w  .  j  a  v  a2  s  .  c  om*/
        item.setTitle(getString(R.string.edit_next));
    }

    if (abusefilterEditResult != null) {
        if (abusefilterEditResult.getType() == EditAbuseFilterResult.TYPE_ERROR) {
            item.setEnabled(false);
        } else {
            item.setEnabled(true);
        }
    } else {
        item.setEnabled(sectionTextModified);
    }

    View v = getLayoutInflater().inflate(R.layout.item_edit_actionbar_button, null);
    item.setActionView(v);
    LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT,
            ViewGroup.LayoutParams.MATCH_PARENT);
    v.setLayoutParams(params);
    TextView txtView = v.findViewById(R.id.edit_actionbar_button_text);
    txtView.setText(item.getTitle());
    txtView.setTypeface(null, item.isEnabled() ? Typeface.BOLD : Typeface.NORMAL);
    v.setTag(item);
    v.setClickable(true);
    v.setEnabled(item.isEnabled());
    v.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            onOptionsItemSelected((MenuItem) view.getTag());
        }
    });

    v.setBackgroundColor(ContextCompat.getColor(this,
            item.isEnabled()
                    ? (editPreviewFragment.isActive() ? R.color.accent50
                            : ResourceUtil.getThemedAttributeId(this, R.attr.colorAccent))
                    : R.color.base50));

    return true;
}

From source file:com.github.jthuraisamy.yellowusage.ui.MainActivity.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    MenuItem refreshItem = menu.findItem(R.id.action_refresh);

    Log.d(TAG, "isMobileDataEnabled   = " + isMobileDataEnabled(connectivityManager));
    Log.d(TAG, "isMobileDataConnected = " + isMobileDataConnected(telephonyManager));
    Log.d(TAG, "isWifiConnected       = " + isWifiConnected(wifiManager));

    // Stop refresh icon animation if it's already ongoing.
    if (refreshItemActionView != null)
        refreshItemActionView.clearAnimation();
    refreshItem.setActionView(null);

    boolean waitingForData = (!taskQueue.isEmpty()) && (!isMobileDataConnected(telephonyManager));

    // (Re-)Start preparing refresh icon animation while waiting for mobile data connection.
    if (waitingForData) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        @SuppressLint("InflateParams")
        ImageView animatingRefreshIcon = (ImageView) layoutInflater.inflate(R.layout.icon_refresh, null);
        Animation clockwiseRotation = AnimationUtils.loadAnimation(this, R.anim.counterclockwise_refresh);
        animatingRefreshIcon.startAnimation(clockwiseRotation);
        refreshItem.setActionView(animatingRefreshIcon);

        // getActionView() always returns null in the else block, so it's assigned to a member variable.
        refreshItemActionView = refreshItem.getActionView();
    }/*from w  w  w .j a v  a2 s  .  c o  m*/

    // (Re-)Start refresh icon animation only if there are ongoing tasks.
    if (ongoingTasks > 0) {
        LayoutInflater layoutInflater = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
        @SuppressLint("InflateParams")
        ImageView animatingRefreshIcon = (ImageView) layoutInflater.inflate(R.layout.icon_refresh, null);
        Animation clockwiseRotation = AnimationUtils.loadAnimation(this, R.anim.clockwise_refresh);
        animatingRefreshIcon.startAnimation(clockwiseRotation);
        refreshItem.setActionView(animatingRefreshIcon);

        // getActionView() always returns null in the else block, so it's assigned to a member variable.
        refreshItemActionView = refreshItem.getActionView();
    }

    return super.onPrepareOptionsMenu(menu);
}

From source file:com.money.manager.ex.home.MainActivity.java

private void stopSyncIconRotation(MenuItem item) {
    if (item == null)
        return;/* w w w  .  j  ava2  s . c om*/

    View actionView = item.getActionView();
    if (actionView == null)
        return;

    actionView.clearAnimation();
    item.setActionView(null);
}

From source file:gov.wa.wsdot.android.wsdot.ui.mountainpasses.passitem.MountainPassItemActivity.java

private void startRefreshAnimation() {
    MenuItem item = mToolbar.getMenu().findItem(MENU_ITEM_REFRESH);
    if (item == null) {
        Log.e(TAG, "null");
        return;/*from   www  .  j  a  v a  2 s  .co m*/
    }
    // define the animation for rotation
    Animation animation = new RotateAnimation(360.0f, 0.0f, Animation.RELATIVE_TO_SELF, 0.5f,
            Animation.RELATIVE_TO_SELF, 0.5f);
    animation.setDuration(1000);

    animation.setRepeatCount(Animation.INFINITE);

    animation.setAnimationListener(new Animation.AnimationListener() {
        @Override
        public void onAnimationStart(Animation animation) {
        }

        @Override
        public void onAnimationEnd(Animation animation) {
            mToolbar.getMenu().getItem(MENU_ITEM_REFRESH).setActionView(null);
            mToolbar.getMenu().getItem(MENU_ITEM_REFRESH).setIcon(R.drawable.ic_menu_refresh);
        }

        @Override
        public void onAnimationRepeat(Animation animation) {
        }
    });

    ImageView imageView = new ImageView(this, null, android.R.style.Widget_Material_ActionButton);
    imageView.setImageDrawable(ContextCompat.getDrawable(this, R.drawable.ic_menu_refresh));

    imageView.setPadding(31, imageView.getPaddingTop(), 32, imageView.getPaddingBottom());

    imageView.startAnimation(animation);
    item.setActionView(imageView);

}

From source file:au.org.intersect.faims.android.ui.activity.ShowModuleActivity.java

public boolean onPrepareOptionsMenu(Menu menu) {
    // gps status
    menu.findItem(R.id.action_gps_inactive).setVisible(false);
    menu.findItem(R.id.action_gps_active_has_signal).setVisible(false);
    menu.findItem(R.id.action_gps_active_no_signal).setVisible(false);
    if (gpsDataManager.isExternalGPSStarted() || gpsDataManager.isInternalGPSStarted()) {
        if (gpsDataManager.hasValidExternalGPSSignal() || gpsDataManager.hasValidInternalGPSSignal()) {
            menu.findItem(R.id.action_gps_active_has_signal).setVisible(true);
        } else {/*  w  w  w. j  a va2 s  . c o  m*/
            menu.findItem(R.id.action_gps_active_no_signal).setVisible(true);
        }
    } else {
        menu.findItem(R.id.action_gps_inactive).setVisible(true);
    }

    // tracker status
    menu.findItem(R.id.action_tracker_active_no_gps).setVisible(false);
    menu.findItem(R.id.action_tracker_active_has_gps).setVisible(false);
    menu.findItem(R.id.action_tracker_inactive).setVisible(false);
    if (gpsDataManager.isTrackingStarted()) {
        if (gpsDataManager.hasValidExternalGPSSignal() || gpsDataManager.hasValidInternalGPSSignal()) {
            menu.findItem(R.id.action_tracker_active_has_gps).setVisible(true);
        } else {
            menu.findItem(R.id.action_tracker_active_no_gps).setVisible(true);
        }
    } else {
        menu.findItem(R.id.action_tracker_inactive).setVisible(true);
    }

    // sync status
    menu.findItem(R.id.action_sync).setVisible(false);
    menu.findItem(R.id.action_sync_active).setVisible(false);
    menu.findItem(R.id.action_sync_error).setVisible(false);
    menu.findItem(R.id.action_sync_has_changes).setVisible(false);
    menu.findItem(R.id.action_sync_inactive).setVisible(false);

    syncAnimImage.clearAnimation();

    switch (syncStatus) {
    case ACTIVE_SYNCING:
        MenuItem syncItem = menu.findItem(R.id.action_sync_active).setVisible(true);

        syncAnimImage.startAnimation(rotation);

        syncItem.setActionView(syncAnimImage);

        break;
    case ERROR:
        menu.findItem(R.id.action_sync_error).setVisible(true);
        break;
    case ACTIVE_NO_CHANGES:
        menu.findItem(R.id.action_sync).setVisible(true);
        break;
    case ACTIVE_HAS_CHANGES:
        menu.findItem(R.id.action_sync_has_changes).setVisible(true);
        break;
    default:
        menu.findItem(R.id.action_sync_inactive).setVisible(true);
        break;
    }

    // follow status
    MenuItem distance_text = menu.findItem(R.id.distance_text);
    distance_text.setVisible(pathIndicatorVisible);
    String distanceInfo = pathIndex < 0 ? "" : " to point (" + pathIndex + "/" + pathLength + ")";
    if (pathDistance > 1000) {
        distance_text.setTitle(
                MeasurementUtil.displayAsKiloMeters(pathDistance / 1000, "###,###,###,###.0") + distanceInfo);
    } else {
        distance_text.setTitle(MeasurementUtil.displayAsMeters(pathDistance, "###,###,###,###") + distanceInfo);
    }

    MenuItem direction_text = menu.findItem(R.id.direction_text);
    direction_text.setVisible(pathIndicatorVisible);
    direction_text.setTitle(MeasurementUtil.displayAsDegrees(pathBearing, "###"));

    MenuItem direction_indicator = menu.findItem(R.id.direction_indicator);
    direction_indicator.setVisible(pathIndicatorVisible);
    if (pathHeading != null) {
        if (tempBitmap != null) {
            tempBitmap.recycle();
        }
        if (whiteArrow == null) {
            whiteArrow = new BitmapDrawable(getResources(), UnscaledBitmapLoader.decodeResource(getResources(),
                    au.org.intersect.faims.android.R.drawable.white_arrow));
        }
        if (greyArrow == null) {
            greyArrow = new BitmapDrawable(getResources(), UnscaledBitmapLoader.decodeResource(getResources(),
                    au.org.intersect.faims.android.R.drawable.grey_arrow));
        }

        this.tempBitmap = BitmapUtil.rotateBitmap(pathValid ? whiteArrow.getBitmap() : greyArrow.getBitmap(),
                pathBearing - pathHeading);
        direction_indicator.setIcon(new BitmapDrawable(getResources(), tempBitmap));
    } else {
        direction_indicator.setVisible(false);
    }

    return true;
}