Example usage for android.widget ImageView setVisibility

List of usage examples for android.widget ImageView setVisibility

Introduction

In this page you can find the example usage for android.widget ImageView setVisibility.

Prototype

@RemotableViewMethod
    @Override
    public void setVisibility(int visibility) 

Source Link

Usage

From source file:com.android.launcher3.Launcher.java

/**
 * Finds all the views we need and configure them properly.
 *///from w w w  .  j a  va 2s  .  c o m
private void setupViews() {
    mLauncherView = findViewById(R.id.launcher);
    mDragLayer = (DragLayer) findViewById(R.id.drag_layer);
    mFocusHandler = mDragLayer.getFocusIndicatorHelper();
    mWorkspace = (Workspace) mDragLayer.findViewById(R.id.workspace);
    mQsbContainer = mDragLayer.findViewById(
            mDeviceProfile.isVerticalBarLayout() ? R.id.workspace_blocked_row : R.id.qsb_container);
    mWorkspace.initParentViews(mDragLayer);

    mLauncherView.setSystemUiVisibility(View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN
            | View.SYSTEM_UI_FLAG_LAYOUT_HIDE_NAVIGATION | View.SYSTEM_UI_FLAG_LAYOUT_STABLE);

    // Setup the drag layer
    mDragLayer.setup(this, mDragController, mAllAppsController);

    // Setup the hotseat
    mHotseat = (Hotseat) findViewById(R.id.hotseat);
    if (mHotseat != null) {
        mHotseat.setOnLongClickListener(this);
    }

    // Setup the overview panel
    setupOverviewPanel();

    setuphome();

    // Setup the workspace
    mWorkspace.setHapticFeedbackEnabled(false);
    mWorkspace.setOnLongClickListener(this);
    mWorkspace.setup(mDragController);
    // Until the workspace is bound, ensure that we keep the wallpaper offset locked to the
    // default state, otherwise we will update to the wrong offsets in RTL
    mWorkspace.lockWallpaperToDefaultPage();
    mDragController.addDragListener(mWorkspace);

    // Get the search/delete/uninstall bar
    mDropTargetBar = (DropTargetBar) mDragLayer.findViewById(R.id.drop_target_bar);

    // Setup Apps and Widgets
    mAppsView = (AllAppsContainerView) findViewById(R.id.apps_view);
    mWidgetsView = (WidgetsContainerView) findViewById(R.id.widgets_view);
    if (mLauncherCallbacks != null && mLauncherCallbacks.getAllAppsSearchBarController() != null) {
        mAppsView.setSearchBarController(mLauncherCallbacks.getAllAppsSearchBarController());
    } else {
        mAppsView.setSearchBarController(new DefaultAppSearchController());
    }

    // Setup the drag controller (drop targets have to be added in reverse order in priority)
    mDragController.setDragScoller(mWorkspace);
    mDragController.setScrollView(mDragLayer);
    mDragController.setMoveTarget(mWorkspace);
    mDragController.addDropTarget(mWorkspace);
    mDropTargetBar.setup(mDragController);

    if (FeatureFlags.LAUNCHER3_ALL_APPS_PULL_UP) {
        mAllAppsController.setupViews(mAppsView, mHotseat, mWorkspace);
    }

    if (TestingUtils.MEMORY_DUMP_ENABLED) {
        TestingUtils.addWeightWatcher(this);
    }

    FrameLayout gBar = (FrameLayout) findViewById(R.id.g_bar);

    if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) {
        FrameLayout.LayoutParams gBarLayout = (FrameLayout.LayoutParams) gBar.getLayoutParams();
        gBarLayout.width = Utils.getScreenXDimension(this) - Utils.getScreenXDimension(this) / 6;
        gBar.setLayoutParams(gBarLayout);
    } else {
        FrameLayout.LayoutParams gBarLayout = (FrameLayout.LayoutParams) gBar.getLayoutParams();
        gBarLayout.width = Utils.getScreenYDimension(this) - Utils.getScreenYDimension(this) / 12;
        gBar.setLayoutParams(gBarLayout);
    }

    gBar.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startSearch("", false, null, true);
        }
    });

    ImageView gSearch = (ImageView) findViewById(R.id.g_search);
    gSearch.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View view) {
            startSearch("", false, null, true);
        }
    });

    FrameLayout.LayoutParams gSearchLayout = (FrameLayout.LayoutParams) gSearch.getLayoutParams();
    gSearchLayout.leftMargin = 30;
    gSearch.setLayoutParams(gSearchLayout);

    ImageView gSearchMic = (ImageView) findViewById(R.id.g_search_mic);
    if (IS_ALLOW_MIC) {
        gSearchMic.setVisibility(View.VISIBLE);
        gSearchMic.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(RecognizerIntent.ACTION_RECOGNIZE_SPEECH);
                startActivityForResult(intent, RECOGNIZER_REQ_CODE);
            }
        });
    } else {
        gSearchMic.setVisibility(View.GONE);
    }

    FrameLayout.LayoutParams gSearchMicLayout = (FrameLayout.LayoutParams) gSearchMic.getLayoutParams();
    gSearchMicLayout.rightMargin = 30;
    gSearchMic.setLayoutParams(gSearchMicLayout);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.JELLY_BEAN) {
        if (Utilities.isAllowNightModePrefEnabled(getApplicationContext())) {
            gBar.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.shape_night));
            gSearch.setImageDrawable(
                    ContextCompat.getDrawable(getApplicationContext(), R.drawable.g_icon_night));
            gSearch.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.night_color));
            gSearchMic
                    .setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.mic_night));
            gSearchMic.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), R.color.night_color));
        } else {
            gBar.setBackground(ContextCompat.getDrawable(getApplicationContext(), R.drawable.shape));
            gSearch.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.g_icon));
            gSearch.setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.white));
            gSearchMic.setImageDrawable(ContextCompat.getDrawable(getApplicationContext(), R.drawable.mic));
            gSearchMic
                    .setBackgroundColor(ContextCompat.getColor(getApplicationContext(), android.R.color.white));
        }
    }

    if (!Utilities.isAllowPersisentSearchBarPrefEnabled(getApplicationContext())) {
        gBar.setVisibility(View.GONE);
        gSearch.setVisibility(View.GONE);
        gSearchMic.setVisibility(View.GONE);
    } else {
        gBar.setVisibility(View.VISIBLE);
        gSearch.setVisibility(View.VISIBLE);
        if (IS_ALLOW_MIC) {
            gSearchMic.setVisibility(View.VISIBLE);
        } else {
            gSearchMic.setVisibility(View.GONE);
        }
    }

}

From source file:com.xmobileapp.rockplayer.RockPlayer.java

/*******************************
 * /*from  ww  w.  ja  v  a2 s. c o  m*/
 * hide and show UI components
 * 
 *******************************/
public void hideMainUI() {

    /*
     * Hide main UI components
     */
    this.albumNavigatorLayout.setVisibility(View.GONE);
    this.currentPlayingLayout.setVisibility(View.GONE);
    this.currentAlbumPlayingImageView.setVisibility(View.GONE);
    this.currentAlbumPlayingLayout.setVisibility(View.GONE);
    this.currentAlbumPlayingLayoutOuter.setVisibility(View.GONE);
    this.albumNavigatorList.setVisibility(View.GONE);
    //      this.albumNavigatorTextContainer.setVisibility(View.GONE);
    this.artistNameText.setVisibility(View.GONE);
    this.albumNameText.setVisibility(View.GONE);
    this.songNameText.setVisibility(View.GONE);
    this.songProgressBar.setVisibility(View.GONE);
    this.songDurationText.setVisibility(View.GONE);
    this.songDurationOngoingText.setVisibility(View.GONE);
    findViewById(R.id.forward_image).setVisibility(View.GONE);
    findViewById(R.id.rewind_image).setVisibility(View.GONE);
    findViewById(R.id.current_album_image_play_pause).setVisibility(View.GONE);

    ImageView albumImageOverlay = (ImageView) findViewById(R.id.current_album_image_overlay);
    albumImageOverlay.setVisibility(View.GONE);
}

From source file:com.andrewshu.android.reddit.threads.ThreadsListActivity.java

public static void fillThreadsListItemView(int position, View view, ThingInfo item, ListActivity activity,
        HttpClient client, RedditSettings settings,
        ThumbnailOnClickListenerFactory thumbnailOnClickListenerFactory) {

    Resources res = activity.getResources();

    TextView titleView = (TextView) view.findViewById(R.id.title);
    TextView votesView = (TextView) view.findViewById(R.id.votes);
    TextView numCommentsSubredditView = (TextView) view.findViewById(R.id.numCommentsSubreddit);
    TextView nsfwView = (TextView) view.findViewById(R.id.nsfw);
    //        TextView submissionTimeView = (TextView) view.findViewById(R.id.submissionTime);
    ImageView voteUpView = (ImageView) view.findViewById(R.id.vote_up_image);
    ImageView voteDownView = (ImageView) view.findViewById(R.id.vote_down_image);
    View thumbnailContainer = view.findViewById(R.id.thumbnail_view);
    FrameLayout thumbnailFrame = (FrameLayout) view.findViewById(R.id.thumbnail_frame);
    ImageView thumbnailImageView = (ImageView) view.findViewById(R.id.thumbnail);
    ProgressBar indeterminateProgressBar = (ProgressBar) view.findViewById(R.id.indeterminate_progress);

    // Set the title and domain using a SpannableStringBuilder
    SpannableStringBuilder builder = new SpannableStringBuilder();
    String title = item.getTitle();
    if (title == null)
        title = "";
    SpannableString titleSS = new SpannableString(title);
    int titleLen = title.length();
    titleSS.setSpan(/*  www  . ja  v a 2s.c  o  m*/
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Large)),
            0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    String domain = item.getDomain();
    if (domain == null)
        domain = "";
    int domainLen = domain.length();
    SpannableString domainSS = new SpannableString("(" + item.getDomain() + ")");
    domainSS.setSpan(
            new TextAppearanceSpan(activity,
                    Util.getTextAppearanceResource(settings.getTheme(), android.R.style.TextAppearance_Small)),
            0, domainLen + 2, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

    if (Util.isLightTheme(settings.getTheme())) {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.purple));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        } else {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.blue));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_50)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    } else {
        if (item.isClicked()) {
            ForegroundColorSpan fcs = new ForegroundColorSpan(res.getColor(R.color.gray_50));
            titleSS.setSpan(fcs, 0, titleLen, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
        domainSS.setSpan(new ForegroundColorSpan(res.getColor(R.color.gray_75)), 0, domainLen + 2,
                Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
    }

    builder.append(titleSS).append(" ").append(domainSS);
    titleView.setText(builder);

    votesView.setText("" + item.getScore());
    numCommentsSubredditView.setText(Util.showNumComments(item.getNum_comments()) + "  " + item.getSubreddit());

    if (item.isOver_18()) {
        nsfwView.setVisibility(View.VISIBLE);
    } else {
        nsfwView.setVisibility(View.GONE);
    }

    // Set the up and down arrow colors based on whether user likes
    if (settings.isLoggedIn()) {
        if (item.getLikes() == null) {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.gray_75));
        } else if (item.getLikes() == true) {
            voteUpView.setImageResource(R.drawable.vote_up_red);
            voteDownView.setImageResource(R.drawable.vote_down_gray);
            votesView.setTextColor(res.getColor(R.color.arrow_red));
        } else {
            voteUpView.setImageResource(R.drawable.vote_up_gray);
            voteDownView.setImageResource(R.drawable.vote_down_blue);
            votesView.setTextColor(res.getColor(R.color.arrow_blue));
        }
    } else {
        voteUpView.setImageResource(R.drawable.vote_up_gray);
        voteDownView.setImageResource(R.drawable.vote_down_gray);
        votesView.setTextColor(res.getColor(R.color.gray_75));
    }

    // Thumbnails open links
    if (thumbnailContainer != null) {
        if (Common.shouldLoadThumbnails(activity, settings)) {
            thumbnailContainer.setVisibility(View.VISIBLE);

            if (item.getUrl() != null) {
                OnClickListener thumbnailOnClickListener = thumbnailOnClickListenerFactory
                        .getThumbnailOnClickListener(item, activity);
                if (thumbnailOnClickListener != null) {
                    thumbnailFrame.setOnClickListener(thumbnailOnClickListener);
                }
            }

            // Show thumbnail based on ThingInfo
            if ("default".equals(item.getThumbnail()) || "self".equals(item.getThumbnail())
                    || StringUtils.isEmpty(item.getThumbnail())) {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                thumbnailImageView.setImageResource(R.drawable.go_arrow);
            } else {
                indeterminateProgressBar.setVisibility(View.GONE);
                thumbnailImageView.setVisibility(View.VISIBLE);
                if (item.getThumbnailBitmap() != null) {
                    thumbnailImageView.setImageBitmap(item.getThumbnailBitmap());
                } else {
                    thumbnailImageView.setImageBitmap(null);
                    new ShowThumbnailsTask(activity, client, R.drawable.go_arrow)
                            .execute(new ThumbnailLoadAction(item, thumbnailImageView, position));
                }
            }

            // Set thumbnail background based on current theme
            if (Util.isLightTheme(settings.getTheme()))
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_light);
            else
                thumbnailFrame.setBackgroundResource(R.drawable.thumbnail_background_dark);
        } else {
            // if thumbnails disabled, hide thumbnail icon
            thumbnailContainer.setVisibility(View.GONE);
        }
    }
}

From source file:org.uguess.android.sysinfo.ApplicationManager.java

@Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    rootView = inflater.inflate(R.layout.app_lst_view, container, false);

    ((Button) rootView.findViewById(R.id.btn_export)).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            doExport();//  w  w  w .ja v a 2 s. c o m
        }
    });

    ((Button) rootView.findViewById(R.id.btn_sel_all)).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            toggleAllSelection(true);
        }
    });

    ((Button) rootView.findViewById(R.id.btn_desel_all)).setOnClickListener(new View.OnClickListener() {

        public void onClick(View v) {
            toggleAllSelection(false);
        }
    });

    ListView lstApps = (ListView) rootView.findViewById(android.R.id.list);

    lstApps.setFastScrollEnabled(true);

    registerForContextMenu(lstApps);

    ArrayAdapter<AppInfoHolder> adapter = new ArrayAdapter<AppInfoHolder>(getActivity(), R.layout.app_item) {

        public android.view.View getView(int position, android.view.View convertView,
                android.view.ViewGroup parent) {
            View view;
            TextView txt_name, txt_size, txt_ver, txt_time;
            ImageView img_type;
            CheckBox ckb_app;

            Activity ctx = getActivity();

            if (convertView == null) {
                view = ctx.getLayoutInflater().inflate(R.layout.app_item, parent, false);
            } else {
                view = convertView;
            }

            if (position >= getCount()) {
                return view;
            }

            AppInfoHolder itm = getItem(position);

            txt_name = (TextView) view.findViewById(R.id.app_name);
            if (itm.label != null) {
                txt_name.setText(itm.label);
            } else {
                txt_name.setText(itm.appInfo.packageName);
            }

            if (Util.getBooleanOption(ctx, PSTORE_APPMANAGER, PREF_KEY_SHOW_BACKUP_STATE)) {
                switch (itm.backupState) {
                case 1:
                    txt_name.setTextColor(Color.YELLOW);
                    break;
                case 2:
                    txt_name.setTextColor(0xff00bb00);
                    break;
                case 3:
                    txt_name.setTextColor(0xffF183BD);
                    break;
                default:
                    txt_name.setTextColor(Color.WHITE);
                    break;
                }
            } else {
                txt_name.setTextColor(Color.WHITE);
            }

            txt_ver = (TextView) view.findViewById(R.id.app_version);
            txt_ver.setText(itm.version);

            txt_size = (TextView) view.findViewById(R.id.app_size);
            if (Util.getBooleanOption(ctx, PSTORE_APPMANAGER, PREF_KEY_SHOW_SIZE)) {
                txt_size.setVisibility(View.VISIBLE);

                if (itm.size != null) {
                    txt_size.setText(itm.size);
                } else {
                    txt_size.setText(R.string.computing);
                }
            } else {
                txt_size.setVisibility(View.GONE);
            }

            txt_time = (TextView) view.findViewById(R.id.app_time);
            if (Util.getBooleanOption(ctx, PSTORE_APPMANAGER, PREF_KEY_SHOW_DATE)) {
                txt_time.setVisibility(View.VISIBLE);

                if (itm.appInfo.sourceDir != null) {
                    File f = new File(itm.appInfo.sourceDir);
                    txt_time.setText(DateUtils.formatDateTime(ctx, f.lastModified(), DateUtils.FORMAT_SHOW_YEAR
                            | DateUtils.FORMAT_SHOW_DATE | DateUtils.FORMAT_SHOW_TIME));
                } else {
                    txt_time.setText(R.string.unknown);
                }
            } else {
                txt_time.setVisibility(View.GONE);
            }

            img_type = (ImageView) view.findViewById(R.id.img_app_icon);
            if (Util.getBooleanOption(ctx, PSTORE_APPMANAGER, PREF_KEY_SHOW_ICON)) {
                img_type.setVisibility(View.VISIBLE);

                if (itm.icon != null) {
                    img_type.setImageDrawable(itm.icon);
                } else {
                    try {
                        img_type.setImageDrawable(ctx.getPackageManager().getDefaultActivityIcon());
                    } catch (Exception fe) {
                        img_type.setImageDrawable(null);

                        Log.e(ApplicationManager.class.getName(), fe.getLocalizedMessage());
                    }
                }
            } else {
                img_type.setVisibility(View.GONE);
            }

            ckb_app = (CheckBox) view.findViewById(R.id.ckb_app);
            ckb_app.setTag(position);
            ckb_app.setChecked(itm.checked);
            ckb_app.setOnCheckedChangeListener(checkListener);

            View imgLock = view.findViewById(R.id.img_lock);
            imgLock.setVisibility(itm.isPrivate ? View.VISIBLE : View.GONE);

            return view;
        }
    };

    setListAdapter(adapter);

    return rootView;
}

From source file:com.android.soma.Launcher.java

protected boolean updateGlobalSearchIcon() {
    final View searchButtonContainer = findViewById(R.id.search_button_container);
    final ImageView searchButton = (ImageView) findViewById(R.id.search_button);
    final View voiceButtonContainer = findViewById(R.id.voice_button_container);
    final View voiceButton = findViewById(R.id.voice_button);

    final SearchManager searchManager = (SearchManager) getSystemService(Context.SEARCH_SERVICE);
    ComponentName activityName = searchManager.getGlobalSearchActivity();
    if (activityName != null) {
        int coi = getCurrentOrientationIndexForGlobalIcons();
        sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(R.id.search_button, activityName,
                R.drawable.ic_home_search_normal_holo, TOOLBAR_SEARCH_ICON_METADATA_NAME);
        if (sGlobalSearchIcon[coi] == null) {
            sGlobalSearchIcon[coi] = updateButtonWithIconFromExternalActivity(R.id.search_button, activityName,
                    R.drawable.ic_home_search_normal_holo, TOOLBAR_ICON_METADATA_NAME);
        }/*from w  ww . jav a  2s  .c o m*/

        if (searchButtonContainer != null)
            searchButtonContainer.setVisibility(View.VISIBLE);
        searchButton.setVisibility(View.VISIBLE);
        invalidatePressedFocusedStates(searchButtonContainer, searchButton);
        return true;
    } else {
        // We disable both search and voice search when there is no global search provider
        if (searchButtonContainer != null)
            searchButtonContainer.setVisibility(View.GONE);
        if (voiceButtonContainer != null)
            voiceButtonContainer.setVisibility(View.GONE);
        if (searchButton != null)
            searchButton.setVisibility(View.GONE);
        if (voiceButton != null)
            voiceButton.setVisibility(View.GONE);
        updateVoiceButtonProxyVisible(false);
        return false;
    }
}

From source file:org.openhab.habdroid.ui.OpenHABWidgetSettingsAdapter.java

@Override
public View getView(int position, View convertView, ViewGroup parent) {
    /* TODO: This definitely needs some huge refactoring
     *///w ww  . j  a v a  2s.co m
    final int pos = position;

    RelativeLayout widgetView;
    TextView labelTextView;
    ImageView roomEditView;
    int widgetLayout = 0;
    OpenHABWidget openHABWidget = getItem(position);
    switch (this.getItemViewType(position)) {
    case TYPE_FRAME:
        widgetLayout = R.layout.openhabwidgetlist_frameitem;
        break;
    case TYPE_GROUP:
        widgetLayout = R.layout.openhabwidget_settings_item;
        break;

    case TYPE_IMAGE:
        widgetLayout = R.layout.openhabwidgetlist_imageitem;
        break;

    case TYPE_CHART:
        widgetLayout = R.layout.openhabwidgetlist_chartitem;
        break;
    case TYPE_VIDEO:
        widgetLayout = R.layout.openhabwidgetlist_videoitem;
        break;
    case TYPE_WEB:
        widgetLayout = R.layout.openhabwidgetlist_webitem;
        break;
    default:
        widgetLayout = R.layout.openhabwidget_settings_item;
        break;
    }
    if (convertView == null) {
        widgetView = new RelativeLayout(getContext());
        String inflater = Context.LAYOUT_INFLATER_SERVICE;
        LayoutInflater vi;
        vi = (LayoutInflater) getContext().getSystemService(inflater);
        vi.inflate(widgetLayout, widgetView, true);
    } else {
        widgetView = (RelativeLayout) convertView;
    }
    switch (getItemViewType(position)) {
    case TYPE_FRAME:
        labelTextView = (TextView) widgetView.findViewById(R.id.framelabel);
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        widgetView.setClickable(false);
        if (openHABWidget.getLabel().length() > 0) { // hide empty frames
            widgetView.setVisibility(View.VISIBLE);
            labelTextView.setVisibility(View.VISIBLE);
        } else {
            widgetView.setVisibility(View.GONE);
            labelTextView.setVisibility(View.GONE);
        }
        break;
    case TYPE_IMAGE:
        MySmartImageView imageImage = (MySmartImageView) widgetView.findViewById(R.id.imageimage);
        imageImage.setImageUrl(ensureAbsoluteURL(openHABBaseUrl, openHABWidget.getUrl()), false);
        if (openHABWidget.getRefresh() > 0) {
            imageImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(imageImage);
        }
        break;
    case TYPE_CHART:
        MySmartImageView chartImage = (MySmartImageView) widgetView.findViewById(R.id.chartimage);
        OpenHABItem chartItem = openHABWidget.getItem();
        Random random = new Random();
        String chartUrl = "";
        if (chartItem.getType().equals("GroupItem")) {
            chartUrl = openHABBaseUrl + "rrdchart.png?groups=" + chartItem.getName() + "&period="
                    + openHABWidget.getPeriod() + "&random=" + String.valueOf(random.nextInt());
        }
        Log.i("OpenHABWidgetAdapter", "Chart url = " + chartUrl);
        chartImage.setImageUrl(chartUrl, false);
        // TODO: This is quite dirty fix to make charts look full screen width on all displays
        ViewGroup.LayoutParams chartLayoutParams = chartImage.getLayoutParams();
        int screenWidth = ((WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE))
                .getDefaultDisplay().getWidth();
        chartLayoutParams.height = (int) (screenWidth / 1.88);
        chartImage.setLayoutParams(chartLayoutParams);
        if (openHABWidget.getRefresh() > 0) {
            chartImage.setRefreshRate(openHABWidget.getRefresh());
            refreshImageList.add(chartImage);
        }
        Log.i("OpenHABWidgetAdapter",
                "chart size = " + chartLayoutParams.width + " " + chartLayoutParams.height);
        break;
    case TYPE_VIDEO:
        VideoView videoVideo = (VideoView) widgetView.findViewById(R.id.videovideo);
        Log.i("OpenHABWidgetAdapter", "Opening video at " + openHABWidget.getUrl());
        // TODO: This is quite dirty fix to make video look maximum available size on all screens
        WindowManager wm = (WindowManager) getContext().getSystemService(Context.WINDOW_SERVICE);
        ViewGroup.LayoutParams videoLayoutParams = videoVideo.getLayoutParams();
        videoLayoutParams.height = (int) (wm.getDefaultDisplay().getWidth() / 1.77);
        videoVideo.setLayoutParams(videoLayoutParams);
        // We don't have any event handler to know if the VideoView is on the screen
        // so we manage an array of all videos to stop them when user leaves the page
        if (!videoWidgetList.contains(videoVideo))
            videoWidgetList.add(videoVideo);
        // Start video
        if (!videoVideo.isPlaying()) {
            videoVideo.setVideoURI(Uri.parse(openHABWidget.getUrl()));
            videoVideo.start();
        }
        Log.i("OpenHABWidgetAdapter", "Video height is " + videoVideo.getHeight());
        break;
    case TYPE_WEB:
        WebView webWeb = (WebView) widgetView.findViewById(R.id.webweb);
        if (openHABWidget.getHeight() > 0) {
            ViewGroup.LayoutParams webLayoutParams = webWeb.getLayoutParams();
            webLayoutParams.height = openHABWidget.getHeight() * 80;
            webWeb.setLayoutParams(webLayoutParams);
        }
        webWeb.setWebViewClient(new WebViewClient());
        webWeb.loadUrl(openHABWidget.getUrl());
        break;

    default:
        labelTextView = (TextView) widgetView.findViewById(R.id.itemlabel);
        roomEditView = (ImageView) widgetView.findViewById(R.id.editimg);
        if (null != roomEditView) {
            roomEditView.setVisibility(View.VISIBLE);
            roomEditView.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View v) {
                    // TODO Auto-generated method stub

                    if (null != listItemListener)
                        listItemListener.onEditClickListener(pos);
                }
            });
        }
        if (labelTextView != null)
            labelTextView.setText(openHABWidget.getLabel());
        MySmartImageView sliderImage = (MySmartImageView) widgetView.findViewById(R.id.itemimage);
        sliderImage.setImageUrl(openHABBaseUrl + "images/" + openHABWidget.getIcon() + ".png");
        break;
    }
    LinearLayout dividerLayout = (LinearLayout) widgetView.findViewById(R.id.listdivider);
    if (dividerLayout != null) {
        if (position < this.getCount() - 1) {
            if (this.getItemViewType(position + 1) == TYPE_FRAME) {
                dividerLayout.setVisibility(View.GONE); // hide dividers before frame widgets
            } else {
                dividerLayout.setVisibility(View.VISIBLE); // show dividers for all others
            }
        } else { // last widget in the list, hide divider
            dividerLayout.setVisibility(View.GONE);
        }
    }
    return widgetView;
}

From source file:fr.shywim.antoinedaniel.ui.fragment.VideoDetailsFragment.java

private void bindSound(View view, Cursor cursor) {
    AppState appState = AppState.getInstance();

    final View card = view;
    final View downloadFrame = view.findViewById(R.id.sound_download_frame);
    final TextView tv = (TextView) view.findViewById(R.id.grid_text);
    final SquareImageView siv = (SquareImageView) view.findViewById(R.id.grid_image);
    final ImageView star = (ImageView) view.findViewById(R.id.ic_sound_fav);
    final ImageView menu = (ImageView) view.findViewById(R.id.ic_sound_menu);

    final String soundName = cursor
            .getString(cursor.getColumnIndex(ProviderContract.SoundEntry.COLUMN_SOUND_NAME));
    String imgId = cursor.getString(cursor.getColumnIndex(ProviderContract.SoundEntry.COLUMN_IMAGE_NAME));
    final String description = cursor.getString(cursor.getColumnIndex(ProviderContract.SoundEntry.COLUMN_DESC));
    final boolean favorite = appState.favSounds.contains(soundName)
            || cursor.getInt(cursor.getColumnIndex(ProviderContract.SoundEntry.COLUMN_FAVORITE)) == 1;
    final boolean widget = appState.widgetSounds.contains(soundName)
            || cursor.getInt(cursor.getColumnIndex(ProviderContract.SoundEntry.COLUMN_WIDGET)) == 1;
    final boolean downloaded = cursor
            .getInt(cursor.getColumnIndex(ProviderContract.SoundEntry.COLUMN_DOWNLOADED)) != 0;

    new Handler().post(new Runnable() {
        @Override//ww  w.ja  va 2  s. co  m
        public void run() {
            ContentValues cv = new ContentValues();
            File sndFile = new File(mContext.getExternalFilesDir(null) + "/snd/" + soundName + ".ogg");

            if (downloaded && !sndFile.exists()) {
                cv.put(ProviderContract.SoundEntry.COLUMN_DOWNLOADED, 0);
                mContext.getContentResolver().update(
                        Uri.withAppendedPath(ProviderConstants.SOUND_DOWNLOAD_NOTIFY_URI, soundName), cv, null,
                        null);
            }
        }
    });

    final View.OnClickListener playSound = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String category = mContext.getString(R.string.ana_cat_sound);
            String action = mContext.getString(R.string.ana_act_play);

            Bundle extras = new Bundle();
            extras.putString(SoundFragment.SOUND_TO_PLAY, soundName);
            extras.putBoolean(SoundFragment.LOOP, SoundUtils.isLoopingSet());
            Intent intent = new Intent(mContext, SoundService.class);
            intent.putExtras(extras);

            mContext.startService(intent);
            AnalyticsUtils.sendEvent(category, action, soundName);
        }
    };

    final View.OnClickListener downloadSound = new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            card.setOnClickListener(null);
            RotateAnimation animation = new RotateAnimation(0, 360, Animation.RELATIVE_TO_SELF, 0.5f,
                    Animation.RELATIVE_TO_SELF, 0.5f);
            animation.setInterpolator(new BounceInterpolator());
            animation.setFillAfter(true);
            animation.setFillEnabled(true);
            animation.setDuration(1000);
            animation.setRepeatCount(Animation.INFINITE);
            animation.setRepeatMode(Animation.RESTART);
            downloadFrame.findViewById(R.id.sound_download_icon).startAnimation(animation);

            DownloadService.startActionDownloadSound(mContext, soundName,
                    new SoundUtils.DownloadResultReceiver(new Handler(), downloadFrame, playSound, this));
        }
    };

    if (downloaded) {
        downloadFrame.setVisibility(View.GONE);
        downloadFrame.findViewById(R.id.sound_download_icon).clearAnimation();
        card.setOnClickListener(playSound);
    } else {
        downloadFrame.setAlpha(1);
        downloadFrame.findViewById(R.id.sound_download_icon).setScaleX(1);
        downloadFrame.findViewById(R.id.sound_download_icon).setScaleY(1);
        downloadFrame.setVisibility(View.VISIBLE);
        card.setOnClickListener(downloadSound);
    }

    menu.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            final ImageView menuIc = (ImageView) v;
            PopupMenu popup = new PopupMenu(mContext, menuIc);
            Menu menu = popup.getMenu();
            popup.getMenuInflater().inflate(R.menu.sound_menu, menu);

            if (favorite)
                menu.findItem(R.id.action_sound_fav).setTitle("Retirer des favoris");
            if (widget)
                menu.findItem(R.id.action_sound_wid).setTitle("Retirer du widget");

            popup.setOnMenuItemClickListener(new PopupMenu.OnMenuItemClickListener() {
                @Override
                public boolean onMenuItemClick(MenuItem item) {
                    switch (item.getItemId()) {
                    case R.id.action_sound_fav:
                        SoundUtils.addRemoveFavorite(mContext, soundName);
                        return true;
                    case R.id.action_sound_wid:
                        SoundUtils.addRemoveWidget(mContext, soundName);
                        return true;
                    /*case R.id.action_sound_add:
                       return true;*/
                    case R.id.action_sound_ring:
                        SoundUtils.addRingtone(mContext, soundName, description);
                        return true;
                    case R.id.action_sound_share:
                        AnalyticsUtils.sendEvent(mContext.getString(R.string.ana_cat_soundcontext),
                                mContext.getString(R.string.ana_act_weblink), soundName);
                        ClipboardManager clipboard = (ClipboardManager) mContext
                                .getSystemService(Context.CLIPBOARD_SERVICE);
                        ClipData clip = ClipData.newPlainText("BAD link", "http://bad.shywim.fr/" + soundName);
                        clipboard.setPrimaryClip(clip);
                        Toast.makeText(mContext, R.string.toast_link_copied, Toast.LENGTH_LONG).show();
                        return true;
                    case R.id.action_sound_delete:
                        SoundUtils.delete(mContext, soundName);
                        return true;
                    default:
                        return false;
                    }
                }
            });

            popup.setOnDismissListener(new PopupMenu.OnDismissListener() {
                @Override
                public void onDismiss(PopupMenu menu) {
                    menuIc.setColorFilter(mContext.getResources().getColor(R.color.text_caption_dark));
                }
            });
            menuIc.setColorFilter(mContext.getResources().getColor(R.color.black));

            popup.show();
        }
    });

    tv.setText(description);
    siv.setTag(imgId);

    if (appState.favSounds.contains(soundName)) {
        star.setVisibility(View.VISIBLE);
    } else if (favorite) {
        star.setVisibility(View.VISIBLE);
        appState.favSounds.add(soundName);
    } else {
        star.setVisibility(View.INVISIBLE);
    }

    File file = new File(mContext.getExternalFilesDir(null) + "/img/" + imgId + ".jpg");
    Picasso.with(mContext).load(file).placeholder(R.drawable.noimg).fit().into(siv);
}

From source file:org.thoughtcrime.securesms.ProfileFragment.java

private void refreshLayout() {
    gDataPreferences = new GDataPreferences(getActivity());
    boolean isMyProfile = (GUtil.numberToLong(gDataPreferences.getE164Number() + "") + "")
            .contains(GUtil.numberToLong(profileId) + "");

    layout_status = (RelativeLayout) getView().findViewById(R.id.layout_status);
    layout_phone = (RelativeLayout) getView().findViewById(R.id.layout_phone);
    layout_group = (RelativeLayout) getView().findViewById(R.id.layout_member);

    statusDate = (TextView) getView().findViewById(R.id.profile__date);
    leaveGroup = (Button) getView().findViewById(R.id.buttonLeaveGroup);
    profileHeader = (TextView) getView().findViewById(R.id.profile_header);
    profileStatus = (AutoCompleteTextView) getView().findViewById(R.id.profile_status);
    xCloseButton = (ImageView) getView().findViewById(R.id.profile_close);
    imageText = (TextView) getView().findViewById(R.id.image_text);
    profilePhone = (TextView) getView().findViewById(R.id.profile_phone);
    groupMember = (ListView) getView().findViewById(R.id.selected_contacts_list);
    historyLayout = (LinearLayout) getView().findViewById(R.id.historylayout);
    historyContentTextView = (TextView) getView().findViewById(R.id.history_content);
    historyScrollView = (HorizontalScrollView) getView().findViewById(R.id.horizontal_scroll);
    recipientsPanel = (PushRecipientsPanel) getView().findViewById(R.id.recipients);
    profilePhone.setText(phonenumber);//from w  w w  .j a va 2s.  c  o m
    profilePicture = (ThumbnailView) getView().findViewById(R.id.profile_picture);
    phoneCall = (ImageView) getView().findViewById(R.id.phone_call);
    (getView().findViewById(R.id.contacts_button)).setOnClickListener(new AddRecipientButtonListener());
    historyLine = (RelativeLayout) getView().findViewById(R.id.layout_history);
    recipient = recipients.getPrimaryRecipient();
    attachmentAdapter = new ProfileImageTypeSelectorAdapter(getActivity());
    scrollView = (ScrollView) getView().findViewById(R.id.scrollView);
    seekBarFont = (SeekBar) getView().findViewById(R.id.seekbar_font);
    chatPartnersColor = (CheckBox) getView().findViewById(R.id.enabled_chat_partners_color);
    colorDefault = (CheckBox) getView().findViewById(R.id.color_default);
    layoutColor = (RelativeLayout) getView().findViewById(R.id.layout_color);
    floatingActionColorButton = (FloatingActionButton) getView().findViewById(R.id.fab_new_color);
    final ImageView profileStatusEdit = (ImageView) getView().findViewById(R.id.profile_status_edit);

    if (!isGroup) {
        ImageSlide slide = ProfileAccessor.getProfileAsImageSlide(getActivity(), masterSecret, profileId);
        if (slide != null && !isMyProfile) {
            if (masterSecret != null) {
                try {
                    profilePicture.setImageResource(slide, masterSecret);
                } catch (IllegalStateException e) {
                    Log.w("GDATA", "Unable to load profile image");
                }
                profileStatus.setText(ProfileAccessor.getProfileStatusForRecepient(getActivity(), profileId),
                        TextView.BufferType.EDITABLE);
                profileStatus.setEnabled(false);
                layout_status.setOnTouchListener(new View.OnTouchListener() {
                    @Override
                    public boolean onTouch(View view, MotionEvent motionEvent) {
                        profileStatusEdit.performClick();
                        return false;
                    }
                });
                statusDate.setText(GUtil.getLocalDate(
                        ProfileAccessor.getProfileUpdateTimeForRecepient(getActivity(), profileId),
                        getActivity().getApplicationContext()));
                imageText.setText(recipient.getName());
            }
            profilePicture.setThumbnailClickListener(new ThumbnailClickListener());
        } else if (ProfileAccessor.getMyProfilePicture(getActivity()).hasImage() && isMyProfile) {
            profileStatus.setText(ProfileAccessor.getProfileStatus(getActivity()),
                    TextView.BufferType.EDITABLE);
            imageText.setText(getString(R.string.MediaPreviewActivity_you));
            initColorSeekbar();
            profilePicture.setThumbnailClickListener(new ThumbnailClickListener());
            if ((ProfileAccessor.getMyProfilePicture(getActivity()).getUri() + "").equals("")) {
                profilePicture.setImageBitmap(ContactPhotoFactory.getDefaultContactPhoto(getActivity()));
            } else {
                profilePicture.setImageResource(ProfileAccessor.getMyProfilePicture(getActivity()));
            }
            historyLine.setVisibility(View.GONE);
        } else {
            imageText.setText(recipient.getName());
            profilePicture.setImageBitmap(recipient.getContactPhoto());
        }
        layout_group.setVisibility(View.GONE);
    } else {
        String groupName = recipient.getName();
        Bitmap avatar = recipient.getContactPhoto();
        String encodedGroupId = recipient.getNumber();
        if (encodedGroupId != null) {
            try {
                groupId = GroupUtil.getDecodedId(encodedGroupId);
            } catch (IOException ioe) {
                groupId = null;
            }
        }
        GroupDatabase db = DatabaseFactory.getGroupDatabase(getActivity());
        Recipients recipients = db.getGroupMembers(groupId, false);

        recipientsPanel.setPanelChangeListener(new PushRecipientsPanel.RecipientsPanelChangedListener() {
            @Override
            public void onRecipientsPanelUpdate(Recipients recipients) {
                Log.w("GDATA", "onRecipientsPanelUpdate received.");
                if (recipients != null) {
                    addAllSelectedContacts(recipients.getRecipientsList());
                    syncAdapterWithSelectedContacts();
                }
            }
        });

        if (recipients != null) {
            final List<Recipient> recipientList = recipients.getRecipientsList();
            if (recipientList != null) {
                if (existingContacts == null)
                    existingContacts = new HashSet<>(recipientList.size());
                existingContacts.addAll(recipientList);
            }
            if (recipientList != null) {
                if (existingContacts == null)
                    existingContacts = new HashSet<>(recipientList.size());
                existingContacts.addAll(recipientList);
            }

            SelectedRecipientsAdapter adapter = new SelectedRecipientsAdapter(getActivity(), android.R.id.text1,
                    new ArrayList<SelectedRecipientsAdapter.RecipientWrapper>());
            adapter.clear();

            if (existingContacts != null) {
                for (Recipient contact : existingContacts) {
                    adapter.add(new SelectedRecipientsAdapter.RecipientWrapper(contact, false));
                }
            }
            adapter.setMasterSecret(masterSecret);
            adapter.setThreadId(threadId);
            adapter.setOnRecipientDeletedListener(new SelectedRecipientsAdapter.OnRecipientDeletedListener() {
                @Override
                public void onRecipientDeleted(Recipient recipient) {
                    removeSelectedContact(recipient);
                }
            });
            groupMember.setAdapter(adapter);
            adapter.notifyDataSetChanged();
        }
        if (avatar != null) {
            profilePicture.setVisibility(View.GONE);
            getView().findViewById(R.id.profile_picture_group).setVisibility(View.VISIBLE);
            scaleImage((ImageView) getView().findViewById(R.id.profile_picture_group), avatar);
        }
        imageText.setText(groupName);
        if (profileStatusString.equals("")) {
            profileStatus.setText(groupName);
        }
        layout_phone.setVisibility(View.GONE);

        leaveGroup.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                if (isActiveGroup()) {
                    handleLeavePushGroup();
                } else {
                    handleDeleteThread();
                }
            }
        });
        if (!isActiveGroup()) {
            leaveGroup.setText(getString(R.string.conversation__menu_delete_thread));
        }

        heightMemberList = GUtil.setListViewHeightBasedOnChildren(groupMember);
    }
    ImageView profileImageEdit = (ImageView) getView().findViewById(R.id.profile_picture_edit);
    ImageView profileImageDelete = (ImageView) getView().findViewById(R.id.profile_picture_delete);
    if (!isMyProfile && !isGroup) {
        profileStatusEdit.setVisibility(View.GONE);
        profileImageDelete.setVisibility(View.GONE);
        profileImageEdit.setVisibility(View.GONE);
    } else {
        if (isGroup) {
            profileImageDelete.setVisibility(View.GONE);
            profileHeader.setText(getString(R.string.group_title));
        } else {
            profileImageDelete.setVisibility(View.VISIBLE);
        }
        profileStatusEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                profileStatus.setEnabled(!profileStatus.isEnabled());
                if (!profileStatus.isEnabled()) {
                    hasChanged = true;
                    hasLeft = false;
                    profileStatusEdit.setImageDrawable(getResources().getDrawable(R.drawable.ic_content_edit));

                    InputMethodManager imm = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(profileStatus.getWindowToken(), 0);
                    if (isGroup) {
                        new UpdateWhisperGroupAsyncTask().execute();
                    } else {
                        ProfileAccessor.setProfileStatus(getActivity(), profileStatus.getText() + "");
                    }
                } else {
                    profileStatusEdit
                            .setImageDrawable(getResources().getDrawable(R.drawable.ic_send_sms_gdata));
                    profileStatus.showDropDown();
                    profileStatus.requestFocus();
                }
            }
        });
        profileImageDelete.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                hasChanged = true;
                hasLeft = false;
                ProfileAccessor.deleteMyProfilePicture(getActivity());
                refreshLayout();
                profileStatus.dismissDropDown();
                gDataPreferences.hasProfileImageChanged(true);
            }
        });
        profileImageEdit.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                gDataPreferences.hasProfileImageChanged(true);
                hasChanged = true;
                hasLeft = false;
                handleAddAttachment();
            }
        });
    }
    if (isMyProfile) {
        ArrayAdapter<String> adapter = new ArrayAdapter<String>(getActivity(),
                android.R.layout.simple_dropdown_item_1line,
                getResources().getStringArray(R.array.status_suggestions));
        profileStatus.setAdapter(adapter);
        profileStatus.setCompletionHint(getString(R.string.status_hint));
        profileStatus.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                profileStatus.dismissDropDown();
            }
        });
        profileStatus.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> adapterView, View view, int i, long l) {
                profileStatus.setEnabled(!profileStatus.isEnabled());
                if (!profileStatus.isEnabled()) {
                    hasChanged = true;
                    hasLeft = false;
                    profileStatusEdit.setImageDrawable(getResources().getDrawable(R.drawable.ic_content_edit));

                    InputMethodManager imm = (InputMethodManager) getActivity()
                            .getSystemService(Context.INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(profileStatus.getWindowToken(), 0);
                    if (isGroup) {
                        new UpdateWhisperGroupAsyncTask().execute();
                    } else {
                        ProfileAccessor.setProfileStatus(getActivity(), profileStatus.getText() + "");
                    }
                }
            }
        });
    } else {
        //        if(!isMyProfile) {
        setMediaHistoryImages();
    }
    xCloseButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            finishAndSave();
        }
    });
    phoneCall.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            handleDial(recipient);
        }
    });
    final RelativeLayout scrollContainer = (RelativeLayout) getView().findViewById(R.id.scrollContainer);
    final LinearLayout mainLayout = (LinearLayout) getView().findViewById(R.id.mainlayout);
    scrollView.setSmoothScrollingEnabled(true);
    ViewTreeObserver vto = scrollView.getViewTreeObserver();
    vto.addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        public void onGlobalLayout() {
            scrollView.scrollTo(0, mainLayout.getTop() - PADDING_TOP);
        }
    });
    scrollContainer.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            // getActivity().finish();
        }
    });
    onScrollChangeListener = new ViewTreeObserver.OnScrollChangedListener() {

        @Override
        public void onScrollChanged() {
            if (BuildConfig.VERSION_CODE >= 11) {
                scrollContainer.setBackgroundColor(Color.WHITE);
                scrollContainer
                        .setAlpha((float) ((1000.0 / scrollContainer.getHeight()) * scrollView.getHeight()));
            }
            int keyboardHeight = 150;
            int paddingBottom = 250;
            int scrollViewHeight = scrollView.getHeight();
            if (getActivity().getResources()
                    .getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) {
                scrollViewHeight = 2 * scrollViewHeight;
            }
            int heightDiff = scrollView.getRootView().getHeight() - scrollView.getHeight();
            if (pxToDp(heightDiff) > keyboardHeight) {
                keyboardIsVisible = true;
            } else {
                keyboardIsVisible = false;
            }
            if (!keyboardIsVisible) {
                if ((mainLayout.getTop() - scrollViewHeight) > scrollView.getScrollY()
                        - pxToDp(paddingBottom)) {
                    finishAndSave();
                }
                if ((scrollViewHeight + (heightMemberList)) < (scrollView.getScrollY() - mainLayout.getTop())) {
                    finishAndSave();
                }
            }
        }
    };
    scrollView.getViewTreeObserver().addOnScrollChangedListener(onScrollChangeListener);
    scrollView.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {

            ViewTreeObserver observer = scrollView.getViewTreeObserver();
            observer.addOnScrollChangedListener(onScrollChangeListener);
            return false;
        }

    });
}

From source file:com.zoffcc.applications.zanavi.Navit.java

@Override
public boolean onPrepareOptionsMenu(Menu menu) {
    super.onPrepareOptionsMenu(menu);
    ///*from   w w  w . j  av  a  2  s .com*/
    menu.clear();

    // load the menu from XML
    getMenuInflater().inflate(R.menu.actionbaricons, menu);

    // NavitOverflowMenuItemID = R.id.item_overflow_menu_button;
    menu.findItem(R.id.share_menu_destination).setTitle(Navit.get_text("Share Destination"));
    menu.findItem(R.id.share_menu_location).setTitle(Navit.get_text("Share my Location"));
    menu.findItem(R.id.search_menu_offline).setTitle(get_text("address search (offline)"));
    menu.findItem(R.id.search_menu_online).setTitle(get_text("address search (online)"));
    menu.findItem(R.id.item_recentdest_menu_button).setTitle(get_text("Recent destinations"));
    menu.findItem(R.id.item_settings_menu_button).setTitle(get_text("Settings"));
    menu.findItem(R.id.item_search_menu_button).setTitle(get_text("Search"));

    // --- download icon ---
    menu.findItem(R.id.item_download_menu_button).setTitle(get_text("downloading map"));
    // --- download icon ---

    //
    menu.findItem(R.id.overflow_share_location).setTitle(Navit.get_text("Share my Location"));
    menu.findItem(R.id.overflow_share_destination).setTitle(Navit.get_text("Share Destination"));
    menu.findItem(R.id.overflow_settings).setTitle(Navit.get_text("Settings"));
    menu.findItem(R.id.overflow_zoom_to_route).setTitle(Navit.get_text("Zoom to Route"));

    if (ZANaviNormalDonateActivity.on_amazon_device) {
        menu.findItem(R.id.overflow_donate_item).setTitle(Navit.get_text("Donate"));
    } else {
        menu.findItem(R.id.overflow_donate_item).setTitle(Navit.get_text("Donate with Google Play"));
    }
    menu.findItem(R.id.overflow_donate_bitcoins_item).setTitle(Navit.get_text("Donate with Bitcoin"));
    //. TRANSLATORS: text to translate is: exit ZANavi
    menu.findItem(R.id.overflow_exit).setTitle(Navit.get_text("exit navit"));
    menu.findItem(R.id.overflow_toggle_poi).setTitle(Navit.get_text("toggle POI"));
    menu.findItem(R.id.overflow_announcer_on).setTitle(Navit.get_text("Announcer On"));
    menu.findItem(R.id.overflow_announcer_off).setTitle(Navit.get_text("Announcer Off"));
    menu.findItem(R.id.overflow_download_maps).setTitle(Navit.get_text("download maps"));
    menu.findItem(R.id.overflow_delete_maps).setTitle(Navit.get_text("delete maps"));
    menu.findItem(R.id.overflow_maps_age).setTitle(Navit.get_text("show Maps age"));
    menu.findItem(R.id.overflow_coord_dialog).setTitle(Navit.get_text("Coord Dialog"));
    menu.findItem(R.id.overflow_add_traffic_block).setTitle(Navit.get_text("add Traffic block"));
    menu.findItem(R.id.overflow_clear_traffic_block).setTitle(Navit.get_text("clear Traffic blocks"));
    menu.findItem(R.id.overflow_convert_gpx_file).setTitle(Navit.get_text("convert GPX file"));
    menu.findItem(R.id.overflow_replay_gps_file).setTitle(Navit.get_text("replay a ZANavi gps file"));
    menu.findItem(R.id.overflow_yaml_tests).setTitle(Navit.get_text("run YAML tests"));
    menu.findItem(R.id.overflow_clear_gpx_map).setTitle(Navit.get_text("clear GPX map"));
    // menu.findItem(R.id.overflow_dummy2)
    menu.findItem(R.id.overflow_demo_v_normal).setTitle(get_text("Demo Vehicle") + " [normal]");
    menu.findItem(R.id.overflow_demo_v_fast).setTitle(get_text("Demo Vehicle") + " [fast]");
    menu.findItem(R.id.overflow_speech_texts).setTitle(Navit.get_text("Speech Texts"));
    menu.findItem(R.id.overflow_nav_commands).setTitle(Navit.get_text("Nav. Commands"));
    menu.findItem(R.id.overflow_toggle_route_graph).setTitle(Navit.get_text("toggle Routegraph"));
    //menu.findItem(R.id.overflow_dummy1)
    menu.findItem(R.id.overflow_export_map_points_to_sdcard).setTitle(Navit.get_text("export Destinations"));
    menu.findItem(R.id.overflow_import_map_points_from_sdcard).setTitle(Navit.get_text("import Destinations"));
    menu.findItem(R.id.overflow_send_feedback).setTitle(Navit.get_text("send feedback"));
    menu.findItem(R.id.overflow_online_help).setTitle(Navit.get_text("online Help"));
    menu.findItem(R.id.overflow_about).setTitle(Navit.get_text("About"));
    //. TRANSLATORS: it means: "show current target in google maps"
    //. TRANSLATORS: please keep this text short, to fit in the android menu!
    menu.findItem(R.id.overflow_target_in_gmaps).setTitle(Navit.get_text("Target in gmaps"));
    //
    //
    menu.findItem(R.id.item_share_menu_button).setTitle(get_text("Share"));

    Display display_ = getWindowManager().getDefaultDisplay();
    Log.e("Navit", "Navit width in DP -> " + display_.getWidth() / Navit.metrics.density);
    Log.e("Navit", "Navit width in DP -> density=" + Navit.metrics.density);

    try {
        View v4 = findViewById(R.id.item_settings_menu_button);
        // Log.e("Navit", "Navit width in DP -> v4=" + v4);
        if ((v4 != null) && (v4.getWidth() > 0)) {
            Log.e("Navit", "Navit width in DP -> v4.w=" + v4.getWidth());
            MenuItem menuItem = menu.findItem(R.id.item_settings_menu_button);
            // Log.e("Navit", "Navit width in DP -> mi=" + menuItem);
            // Log.e("Navit", "Navit width in DP -> i=" + menuItem.getIcon());
            Log.e("Navit", "Navit width in DP -> i.w=" + menuItem.getIcon().getIntrinsicWidth());
            actionbar_item_width = (int) ((v4.getWidth() + (menuItem.getIcon().getIntrinsicWidth() * 1.5f))
                    / 2);
        } else {
            MenuItem menuItem = menu.findItem(R.id.item_settings_menu_button);
            // Log.e("Navit", "Navit width in DP -> mi=" + menuItem);
            // Log.e("Navit", "Navit width in DP -> i=" + menuItem.getIcon());
            Log.e("Navit", "Navit width in DP -> i.w=" + menuItem.getIcon().getIntrinsicWidth());
            actionbar_item_width = (int) ((menuItem.getIcon().getIntrinsicWidth()) * 1.7f);
        }

        actionbar_items_will_fit = display_.getWidth() / actionbar_item_width;
        Log.e("Navit", "Navit width in DP -> number of items that will fit=" + actionbar_items_will_fit);
        if (actionbar_items_will_fit > 6) // now we need to fit max. 6 items on actionbar
        {
            actionbar_all_items_will_fit = true;
        } else {
            actionbar_all_items_will_fit = false;
        }
    } catch (Exception e) {
        if ((display_.getWidth() / Navit.metrics.density) < NAVIT_MIN_HORIZONTAL_DP_FOR_ACTIONBAR) {
            actionbar_all_items_will_fit = false;
        } else {
            actionbar_all_items_will_fit = true;
        }
    }

    if (actionbar_all_items_will_fit == false) {
        menu.findItem(R.id.item_share_menu_button).setVisible(false);
        menu.findItem(R.id.overflow_share_location).setVisible(true);
        if (NavitGraphics.CallbackDestinationValid2() == 0) {
            menu.findItem(R.id.overflow_share_destination).setVisible(false);
        } else {
            menu.findItem(R.id.overflow_share_destination).setVisible(true);
        }

        if (actionbar_items_will_fit < 6) {
            // also push the settings icons to overflow menu
            menu.findItem(R.id.item_settings_menu_button).setVisible(false);
            menu.findItem(R.id.overflow_settings).setVisible(true);
        } else {
            menu.findItem(R.id.item_settings_menu_button).setVisible(true);
            menu.findItem(R.id.overflow_settings).setVisible(false);
        }
    } else {
        menu.findItem(R.id.item_settings_menu_button).setVisible(true);
        menu.findItem(R.id.overflow_settings).setVisible(false);
        menu.findItem(R.id.overflow_share_location).setVisible(false);
        menu.findItem(R.id.overflow_share_destination).setVisible(false);
        menu.findItem(R.id.item_share_menu_button).setVisible(true);
    }

    cur_menu = menu;

    System.out.println("down_icon:000");

    try {
        MenuItem downloadViewMenuItem = menu.findItem(R.id.item_download_menu_button);
        System.out.println("down_icon:001");
        downloadViewMenuItem.setVisible(true);
        System.out.println("down_icon:002");
        System.out.println("down_icon:003");
        android.widget.ImageView v = (android.widget.ImageView) MenuItemCompat
                .getActionView(menu.findItem(R.id.item_download_menu_button));
        System.out.println("down_icon:004");
        v.setVisibility(View.VISIBLE);
        if (v != null) {
            System.out.println("down_icon:005");
            v.setImageBitmap(null);
            System.out.println("down_icon:006");

            v.setBackgroundResource(R.drawable.anim_download_icon_2);
            final AnimationDrawable anim = (AnimationDrawable) v.getBackground();

            // ----------------------------------
            // thanks to: http://stackoverflow.com/questions/14686802/animationdrawable-is-not-working-on-2-3-6-android-version
            // ----------------------------------
            v.post(new Runnable() {
                public void run() {
                    try {
                        anim.start();
                        System.out.println("down_icon:006a");
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }
            });

            System.out.println("down_icon:007");

            v.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent mapdownload_cancel_activity = new Intent(Navit.this,
                            ZANaviDownloadMapCancelActivity.class);
                    mapdownload_cancel_activity
                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP | Intent.FLAG_ACTIVITY_SINGLE_TOP);
                    startActivity(mapdownload_cancel_activity);
                }
            });
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("down_icon:099:EE");
    }

    if (actionabar_download_icon_visible) {
        menu.findItem(R.id.item_download_menu_button).setVisible(true);
    } else {
        menu.findItem(R.id.item_download_menu_button).setVisible(false);
    }

    if (NavitGraphics.CallbackDestinationValid2() > 0) {
        menu.findItem(R.id.item_endnavigation_menu_button).setVisible(true);
        menu.findItem(R.id.item_endnavigation_menu_button).setTitle(get_text("Stop Navigation"));
        menu.findItem(R.id.overflow_zoom_to_route).setVisible(true);
        menu.findItem(R.id.overflow_target_in_gmaps).setVisible(true);
        menu.findItem(R.id.share_menu_destination).setVisible(true);
    } else {
        menu.findItem(R.id.item_endnavigation_menu_button).setVisible(false);
        menu.findItem(R.id.overflow_zoom_to_route).setVisible(false);
        menu.findItem(R.id.overflow_target_in_gmaps).setVisible(false);
        menu.findItem(R.id.share_menu_destination).setVisible(false);
    }

    if (Navit_Announcer == true) {
        menu.findItem(R.id.overflow_announcer_off).setVisible(true);
        menu.findItem(R.id.overflow_announcer_on).setVisible(false);
    } else {
        menu.findItem(R.id.overflow_announcer_off).setVisible(false);
        menu.findItem(R.id.overflow_announcer_on).setVisible(true);
    }

    if (p.PREF_enable_debug_functions) {
        menu.findItem(R.id.overflow_dummy2).setVisible(true);
        menu.findItem(R.id.overflow_demo_v_normal).setVisible(true);
        menu.findItem(R.id.overflow_demo_v_fast).setVisible(true);
        menu.findItem(R.id.overflow_speech_texts).setVisible(true);
        menu.findItem(R.id.overflow_nav_commands).setVisible(true);
        menu.findItem(R.id.overflow_toggle_route_graph).setVisible(true);
        menu.findItem(R.id.overflow_replay_gps_file).setVisible(true);
        menu.findItem(R.id.overflow_yaml_tests).setVisible(true);
    } else {
        menu.findItem(R.id.overflow_dummy2).setVisible(false);
        menu.findItem(R.id.overflow_demo_v_normal).setVisible(false);
        menu.findItem(R.id.overflow_demo_v_fast).setVisible(false);
        menu.findItem(R.id.overflow_speech_texts).setVisible(false);
        menu.findItem(R.id.overflow_nav_commands).setVisible(false);
        menu.findItem(R.id.overflow_toggle_route_graph).setVisible(false);
        menu.findItem(R.id.overflow_replay_gps_file).setVisible(false);
        menu.findItem(R.id.overflow_yaml_tests).setVisible(false);
    }

    return true;
}