Example usage for android.widget ProgressBar setVisibility

List of usage examples for android.widget ProgressBar setVisibility

Introduction

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

Prototype

@RemotableViewMethod
public void setVisibility(@Visibility int visibility) 

Source Link

Document

Set the visibility state of this view.

Usage

From source file:im.vector.util.BugReporter.java

/**
 * Send a bug report either with email or with Vector.
 *//*from   w w  w.  j  a  v  a  2  s.co  m*/
public static void sendBugReport() {
    final Activity currentActivity = VectorApp.getCurrentActivity();

    // no current activity so cannot display an alert
    if (null == currentActivity) {
        sendBugReport(VectorApp.getInstance().getApplicationContext(), true, true, "", null);
        return;
    }

    final Context appContext = currentActivity.getApplicationContext();
    LayoutInflater inflater = currentActivity.getLayoutInflater();
    View dialogLayout = inflater.inflate(R.layout.dialog_bug_report, null);

    final AlertDialog.Builder dialog = new AlertDialog.Builder(currentActivity);
    dialog.setTitle(R.string.send_bug_report);
    dialog.setView(dialogLayout);

    final EditText bugReportText = (EditText) dialogLayout.findViewById(R.id.bug_report_edit_text);
    final CheckBox includeLogsButton = (CheckBox) dialogLayout
            .findViewById(R.id.bug_report_button_include_logs);
    final CheckBox includeCrashLogsButton = (CheckBox) dialogLayout
            .findViewById(R.id.bug_report_button_include_crash_logs);

    final ProgressBar progressBar = (ProgressBar) dialogLayout.findViewById(R.id.bug_report_progress_view);
    final TextView progressTextView = (TextView) dialogLayout.findViewById(R.id.bug_report_progress_text_view);

    dialog.setPositiveButton(R.string.send, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // will be overridden to avoid dismissing the dialog while displaying the progress
        }
    });

    dialog.setNegativeButton(R.string.cancel, new DialogInterface.OnClickListener() {
        @Override
        public void onClick(DialogInterface dialog, int which) {
            // will be overridden to avoid dismissing the dialog while displaying the progress
        }
    });

    //
    final AlertDialog bugReportDialog = dialog.show();
    final Button cancelButton = bugReportDialog.getButton(AlertDialog.BUTTON_NEGATIVE);
    final Button sendButton = bugReportDialog.getButton(AlertDialog.BUTTON_POSITIVE);

    if (null != cancelButton) {
        cancelButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // check if there is no upload in progress
                if (includeLogsButton.isEnabled()) {
                    bugReportDialog.dismiss();
                } else {
                    mIsCancelled = true;
                    cancelButton.setEnabled(false);
                }
            }
        });
    }

    if (null != sendButton) {
        sendButton.setEnabled(false);

        sendButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                // disable the active area while uploading the bug report
                bugReportText.setEnabled(false);
                sendButton.setEnabled(false);
                includeLogsButton.setEnabled(false);
                includeCrashLogsButton.setEnabled(false);

                progressTextView.setVisibility(View.VISIBLE);
                progressTextView.setText(appContext.getString(R.string.send_bug_report_progress, 0 + ""));

                progressBar.setVisibility(View.VISIBLE);
                progressBar.setProgress(0);

                sendBugReport(VectorApp.getInstance(), includeLogsButton.isChecked(),
                        includeCrashLogsButton.isChecked(), bugReportText.getText().toString(),
                        new IMXBugReportListener() {
                            @Override
                            public void onUploadFailed(String reason) {
                                try {
                                    if (null != VectorApp.getInstance() && !TextUtils.isEmpty(reason)) {
                                        Toast.makeText(VectorApp.getInstance(),
                                                VectorApp.getInstance()
                                                        .getString(R.string.send_bug_report_failed, reason),
                                                Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadFailed() : failed to display the toast "
                                            + e.getMessage());
                                }

                                try {
                                    // restore the dialog if the upload failed
                                    bugReportText.setEnabled(true);
                                    sendButton.setEnabled(true);
                                    includeLogsButton.setEnabled(true);
                                    includeCrashLogsButton.setEnabled(true);
                                    cancelButton.setEnabled(true);

                                    progressTextView.setVisibility(View.GONE);
                                    progressBar.setVisibility(View.GONE);
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadFailed() : failed to restore the dialog button "
                                            + e.getMessage());

                                    try {
                                        bugReportDialog.dismiss();
                                    } catch (Exception e2) {
                                        Log.e(LOG_TAG, "## onUploadFailed() : failed to dismiss the dialog "
                                                + e2.getMessage());
                                    }
                                }

                                mIsCancelled = false;
                            }

                            @Override
                            public void onUploadCancelled() {
                                onUploadFailed(null);
                            }

                            @Override
                            public void onProgress(int progress) {
                                if (progress > 100) {
                                    Log.e(LOG_TAG, "## onProgress() : progress > 100");
                                    progress = 100;
                                } else if (progress < 0) {
                                    Log.e(LOG_TAG, "## onProgress() : progress < 0");
                                    progress = 0;
                                }

                                progressBar.setProgress(progress);
                                progressTextView.setText(
                                        appContext.getString(R.string.send_bug_report_progress, progress + ""));
                            }

                            @Override
                            public void onUploadSucceed() {
                                try {
                                    if (null != VectorApp.getInstance()) {
                                        Toast.makeText(VectorApp.getInstance(),
                                                VectorApp.getInstance().getString(
                                                        R.string.send_bug_report_sent),
                                                Toast.LENGTH_LONG).show();
                                    }
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadSucceed() : failed to dismiss the toast "
                                            + e.getMessage());
                                }

                                try {
                                    bugReportDialog.dismiss();
                                } catch (Exception e) {
                                    Log.e(LOG_TAG, "## onUploadSucceed() : failed to dismiss the dialog "
                                            + e.getMessage());
                                }
                            }
                        });
            }
        });
    }

    bugReportText.addTextChangedListener(new TextWatcher() {
        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {

        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (null != sendButton) {
                sendButton.setEnabled(bugReportText.getText().toString().length() > 10);
            }
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
}

From source file:com.popdeem.sdk.uikit.activity.PDUIClaimActivity.java

private void performClaimReward(final String message, final String encodedImage, final boolean fromInstagram,
        final boolean fromTwitter, final Boolean fromFacebook) {
    final ProgressBar progressBar = (ProgressBar) findViewById(R.id.pd_progress_bar);
    progressBar.setVisibility(View.VISIBLE);

    final Button shareButton = (Button) findViewById(R.id.pd_claim_share_button);
    shareButton.setEnabled(false);/*from   w ww  .j  a  va 2 s .c  o m*/
    shareButton.animate().alpha(0.5f);
    shareButton.setVisibility(View.GONE);

    claiming = true;
    int postTime = 1;
    if (fromFacebook) {
        postTime = 3000;
    }

    new Handler().postDelayed(new Runnable() {
        @Override
        public void run() {
            String twitterToken = null;
            String twitterSecret = null;
            if (mTwitterSwitch.isChecked() && PDSocialUtils.isTwitterLoggedIn()
                    && TwitterCore.getInstance().getSessionManager().getActiveSession()
                            .getAuthToken().token != null
                    && TwitterCore.getInstance().getSessionManager().getActiveSession()
                            .getAuthToken().secret != null) {
                twitterToken = TwitterCore.getInstance().getSessionManager().getActiveSession()
                        .getAuthToken().token;
                twitterSecret = TwitterCore.getInstance().getSessionManager().getActiveSession()
                        .getAuthToken().secret;
            }

            Realm realm = Realm.getDefaultInstance();
            PDRealmUserLocation userLocation = realm.where(PDRealmUserLocation.class).findFirst();

            PDRealmUserDetails userDetails = realm.where(PDRealmUserDetails.class).findFirst();
            String instagramAccessToken = null;
            if (mInstagramSwitch.isChecked() && userDetails.getUserInstagram() != null
                    && userDetails.getUserInstagram().getAccessToken() != null
                    && !userDetails.getUserInstagram().getAccessToken().isEmpty()) {
                instagramAccessToken = userDetails.getUserInstagram().getAccessToken();
            }

            if (mTaggedNames.size() == 0) {
                PDAbraLogEvent.log(PDAbraConfig.ABRA_EVENT_ADDED_CLAIM_CONTENT,
                        new PDAbraProperties.Builder().add(PDAbraConfig.ABRA_PROPERTYNAME_TAGGED_FRIENDS, "Yes")
                                .add("Friends Count", String.valueOf(mTaggedNames.size())).create());
            }

            progressBar.setVisibility(View.GONE);
            shareButton.setVisibility(View.VISIBLE);
            shareButton.setEnabled(true);
            shareButton.animate().alpha(1.0f);

            if (fromTwitter) {
                finishActivityAfterClaim("twitter");
                realm.close();
                return;
            } else if (fromFacebook) {
                finishActivityAfterClaim("facebook");
                realm.close();
                return;
            } else if (fromInstagram) {
                finishActivityAfterClaim("instagram");
                realm.close();
                return;
            }

            PDAPIClient.instance().claimReward(PDUIClaimActivity.this,
                    mFacebookSwitch.isChecked() ? AccessToken.getCurrentAccessToken().getToken() : null,
                    twitterToken, twitterSecret, instagramAccessToken, mReward.getId(), message, mTaggedNames,
                    mTaggedIds, encodedImage, String.valueOf(userLocation.getLongitude()),
                    String.valueOf(userLocation.getLatitude()), new PDAPICallback<JsonObject>() {
                        @Override
                        public void success(JsonObject jsonObject) {
                            PDLog.d(PDUIClaimActivity.class, "claim: " + jsonObject.toString());
                            progressBar.setVisibility(View.GONE);
                            shareButton.setEnabled(true);
                            shareButton.animate().alpha(1.0f);

                            PDAbraLogEvent.log(PDAbraConfig.ABRA_EVENT_CLAIMED, new PDAbraProperties.Builder()
                                    .add(PDAbraConfig.ABRA_PROPERTYNAME_SOCIAL_NETWORKS,
                                            readableNetworksChosen())
                                    .add(PDAbraConfig.ABRA_PROPERTYNAME_PHOTO, mImageAdded ? "YES" : "NO")
                                    .add(PDAbraConfig.ABRA_PROPERTYNAME_REWARD_TYPE,
                                            PDAbraUtils.keyForRewardType(mReward.getRewardType()))
                                    .create());

                            if (fromInstagram) {
                                //                                    verifyReward();
                                finishActivityAfterClaim("instagram");
                            } else if (fromTwitter) {
                                finishActivityAfterClaim("twitter");
                            } else if (fromFacebook) {
                                finishActivityAfterClaim("facebook");
                            } else {
                                //                            new AlertDialog.Builder(PDUIClaimActivity.this)
                                //                                    .setTitle(R.string.pd_claim_reward_claimed_text)
                                //                                    .setMessage(mReward.getRewardType().equalsIgnoreCase(PDReward.PD_REWARD_TYPE_SWEEPSTAKE) ? R.string.pd_claim_sweepstakes_claimed_success_text : R.string.pd_claim_reward_claimed_success_text)
                                //                                    .setPositiveButton(R.string.pd_go_to_wallet_text, new DialogInterface.OnClickListener() {
                                //                                        @Override
                                //                                        public void onClick(DialogInterface dialog, int which) {
                                //                                            Intent data = new Intent();
                                //                                            data.putExtra("id", mReward.getId());
                                //                                            data.putExtra("verificationNeeded", mInstagramSwitch.isChecked());
                                //                                            setResult(RESULT_OK, data);
                                //                                            finish();
                                //                                        }
                                //                                    })
                                //                                    .create()
                                //                                    .show();
                                Intent data = new Intent();
                                data.putExtra("id", mReward.getId());
                                //                                    data.putExtra("verificationNeeded", mInstagramSwitch.isChecked());
                                data.putExtra("verificationNeeded", false);
                                setResult(RESULT_OK, data);
                                finish();
                                claiming = false;

                            }
                        }

                        @Override
                        public void failure(int statusCode, Exception e) {

                            if (fromInstagram) {
                                finishActivityAfterClaim("instagram");
                            } else if (fromTwitter) {
                                finishActivityAfterClaim("twitter");
                            } else if (fromFacebook) {
                                finishActivityAfterClaim("facebook");
                            }
                            Handler mainHandler = new Handler(Looper.getMainLooper());

                            Runnable myRunnable = new Runnable() {
                                @Override
                                public void run() {
                                    progressBar.setVisibility(View.GONE);
                                    shareButton.setEnabled(true);
                                    shareButton.animate().alpha(1.0f);
                                    if (!fromInstagram) {
                                        showBasicOKAlertDialog(R.string.pd_common_sorry_text,
                                                R.string.pd_common_something_wrong_text);
                                    }
                                }
                            };
                            mainHandler.post(myRunnable);

                        }
                    });
            realm.close();

        }
    }, postTime);

}

From source file:jahirfiquitiva.iconshowcase.activities.ViewerActivity.java

@SuppressWarnings("ResourceAsColor")
@Override/*from  w ww . j  av  a2 s.c o m*/
protected void onCreate(Bundle savedInstanceState) {

    ThemeUtils.onActivityCreateSetTheme(this);

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
        ThemeUtils.onActivityCreateSetNavBar(this);
        Window window = getWindow();
        window.addFlags(WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS);
    }

    super.onCreate(savedInstanceState);

    context = this;

    usePalette = getResources().getBoolean(R.bool.use_palette_api_in_viewer);

    mPrefs = new Preferences(context);

    mPrefs.setActivityVisible(true);

    Intent intent = getIntent();
    String transitionName = intent.getStringExtra("transitionName");

    item = intent.getParcelableExtra("item");

    setContentView(R.layout.wall_viewer_activity);

    toolbar = (Toolbar) findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);

    if (getSupportActionBar() != null) {
        getSupportActionBar().setTitle("");
        getSupportActionBar().setHomeAsUpIndicator(R.drawable.ic_back);
        getSupportActionBar().setHomeButtonEnabled(true);
        getSupportActionBar().setDisplayHomeAsUpEnabled(true);
        getSupportActionBar().setDisplayShowHomeEnabled(true);
    }

    final int iconsColor = ThemeUtils.darkTheme ? ContextCompat.getColor(context, R.color.toolbar_text_dark)
            : ContextCompat.getColor(context, R.color.toolbar_text_light);

    ToolbarColorizer.colorizeToolbar(toolbar, iconsColor);

    toHide1 = (LinearLayout) findViewById(R.id.iconsA);
    toHide2 = (LinearLayout) findViewById(R.id.iconsB);

    int tintLightLighter = ContextCompat.getColor(context, R.color.drawable_base_tint);
    int tintDark = ContextCompat.getColor(context, R.color.drawable_tint_dark);

    Drawable save = ColorUtils.getTintedIcon(context, R.drawable.ic_save,
            ThemeUtils.darkTheme ? tintDark : tintLightLighter);

    Drawable apply = ColorUtils.getTintedIcon(context, R.drawable.ic_apply_wallpaper,
            ThemeUtils.darkTheme ? tintDark : tintLightLighter);

    Drawable info = ColorUtils.getTintedIcon(context, R.drawable.ic_info,
            ThemeUtils.darkTheme ? tintDark : tintLightLighter);

    ImageView saveIV = (ImageView) findViewById(R.id.download);
    if (item.isDownloadable()) {
        saveIV.setImageDrawable(save);
        saveIV.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                if (!PermissionUtils.canAccessStorage(context)) {
                    PermissionUtils.setViewerActivityAction("save");
                    PermissionUtils.requestStoragePermission(context);
                } else {
                    showDialogs("save");
                }
            }
        });
    } else {
        saveIV.setVisibility(View.GONE);
    }

    ImageView applyIV = (ImageView) findViewById(R.id.apply);
    applyIV.setImageDrawable(apply);
    applyIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            showApplyWallpaperDialog(context, item.getWallURL());
        }
    });

    ImageView infoIV = (ImageView) findViewById(R.id.info);
    infoIV.setImageDrawable(info);
    infoIV.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            ISDialogs.showWallpaperDetailsDialog(context, item.getWallName(), item.getWallAuthor(),
                    item.getWallDimensions(), item.getWallCopyright());
        }
    });

    TouchImageView mPhoto = (TouchImageView) findViewById(R.id.big_wallpaper);
    ViewCompat.setTransitionName(mPhoto, transitionName);

    layout = (RelativeLayout) findViewById(R.id.viewerLayout);

    TextView wallNameText = (TextView) findViewById(R.id.wallName);
    wallNameText.setText(item.getWallName());

    Bitmap bmp = null;
    String filename = getIntent().getStringExtra("image");
    try {
        if (filename != null) {
            FileInputStream is = context.openFileInput(filename);
            bmp = BitmapFactory.decodeStream(is);
            is.close();
        } else {
            bmp = null;
        }
    } catch (Exception e) {
        e.printStackTrace();
    }

    int colorFromCachedPic = 0;

    if (bmp != null) {
        colorFromCachedPic = ColorExtractor.getFinalGeneratedIconsColorFromPalette(bmp, usePalette);
    } else {
        colorFromCachedPic = ThemeUtils.darkTheme ? tintDark : tintLightLighter;
    }

    final ProgressBar spinner = (ProgressBar) findViewById(R.id.progress);
    spinner.getIndeterminateDrawable().setColorFilter(colorFromCachedPic, PorterDuff.Mode.SRC_IN);

    ToolbarColorizer.colorizeToolbar(toolbar, colorFromCachedPic);

    Drawable d;
    if (bmp != null) {
        d = new GlideBitmapDrawable(getResources(), bmp);
    } else {
        d = new ColorDrawable(ContextCompat.getColor(context, android.R.color.transparent));
    }

    if (mPrefs.getAnimationsEnabled()) {
        Glide.with(context).load(item.getWallURL()).placeholder(d).diskCacheStrategy(DiskCacheStrategy.SOURCE)
                .fitCenter().listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target,
                            boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                            Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        Bitmap picture = ((GlideBitmapDrawable) resource).getBitmap();
                        ToolbarColorizer.colorizeToolbar(toolbar,
                                ColorExtractor.getFinalGeneratedIconsColorFromPalette(picture, usePalette));
                        spinner.setVisibility(View.GONE);
                        return false;
                    }
                }).into(mPhoto);
    } else {
        Glide.with(context).load(item.getWallURL()).placeholder(d).dontAnimate()
                .diskCacheStrategy(DiskCacheStrategy.SOURCE).fitCenter()
                .listener(new RequestListener<String, GlideDrawable>() {
                    @Override
                    public boolean onException(Exception e, String model, Target<GlideDrawable> target,
                            boolean isFirstResource) {
                        return false;
                    }

                    @Override
                    public boolean onResourceReady(GlideDrawable resource, String model,
                            Target<GlideDrawable> target, boolean isFromMemoryCache, boolean isFirstResource) {
                        Bitmap picture = ((GlideBitmapDrawable) resource).getBitmap();
                        ToolbarColorizer.colorizeToolbar(toolbar,
                                ColorExtractor.getFinalGeneratedIconsColorFromPalette(picture, usePalette));
                        spinner.setVisibility(View.GONE);
                        return false;
                    }
                }).into(mPhoto);
    }
}

From source file:org.quantumbadger.redreader.activities.ImageViewActivity.java

@Override
protected void onCreate(Bundle savedInstanceState) {

    super.onCreate(savedInstanceState);

    final SharedPreferences sharedPreferences = PreferenceManager.getDefaultSharedPreferences(this);
    final boolean solidblack = PrefsUtility.appearance_solidblack(this, sharedPreferences);

    if (solidblack)
        getWindow().setBackgroundDrawable(new ColorDrawable(Color.BLACK));

    final Intent intent = getIntent();

    mUrl = General.uriFromString(intent.getDataString());
    final RedditPost src_post = intent.getParcelableExtra("post");

    if (mUrl == null) {
        General.quickToast(this, "Invalid URL. Trying web browser.");
        revertToWeb();/*from  www.  j  ava2s  .  c o m*/
        return;
    }

    Log.i("ImageViewActivity", "Loading URL " + mUrl.toString());

    final ProgressBar progressBar = new ProgressBar(this, null, android.R.attr.progressBarStyleHorizontal);

    final LinearLayout layout = new LinearLayout(this);
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.addView(progressBar);

    CacheManager.getInstance(this)
            .makeRequest(mRequest = new CacheRequest(mUrl, RedditAccountManager.getAnon(), null,
                    Constants.Priority.IMAGE_VIEW, 0, CacheRequest.DownloadType.IF_NECESSARY,
                    Constants.FileType.IMAGE, false, false, false, this) {

                private void setContentView(View v) {
                    layout.removeAllViews();
                    layout.addView(v);
                    v.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                    v.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                }

                @Override
                protected void onCallbackException(Throwable t) {
                    BugReportActivity.handleGlobalError(context.getApplicationContext(),
                            new RRError(null, null, t));
                }

                @Override
                protected void onDownloadNecessary() {
                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.VISIBLE);
                            progressBar.setIndeterminate(true);
                        }
                    });
                }

                @Override
                protected void onDownloadStarted() {
                }

                @Override
                protected void onFailure(final RequestFailureType type, Throwable t, StatusLine status,
                        final String readableMessage) {

                    final RRError error = General.getGeneralErrorForFailure(context, type, t, status,
                            url.toString());

                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        public void run() {
                            // TODO handle properly
                            mRequest = null;
                            progressBar.setVisibility(View.GONE);
                            layout.addView(new ErrorView(ImageViewActivity.this, error));
                        }
                    });
                }

                @Override
                protected void onProgress(final boolean authorizationInProgress, final long bytesRead,
                        final long totalBytes) {
                    AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                        @Override
                        public void run() {
                            progressBar.setVisibility(View.VISIBLE);
                            progressBar.setIndeterminate(authorizationInProgress);
                            progressBar.setProgress((int) ((100 * bytesRead) / totalBytes));
                        }
                    });
                }

                @Override
                protected void onSuccess(final CacheManager.ReadableCacheFile cacheFile, long timestamp,
                        UUID session, boolean fromCache, final String mimetype) {

                    if (mimetype == null
                            || (!Constants.Mime.isImage(mimetype) && !Constants.Mime.isVideo(mimetype))) {
                        revertToWeb();
                        return;
                    }

                    final InputStream cacheFileInputStream;
                    try {
                        cacheFileInputStream = cacheFile.getInputStream();
                    } catch (IOException e) {
                        notifyFailure(RequestFailureType.PARSE, e, null,
                                "Could not read existing cached image.");
                        return;
                    }

                    if (cacheFileInputStream == null) {
                        notifyFailure(RequestFailureType.CACHE_MISS, null, null, "Could not find cached image");
                        return;
                    }

                    if (Constants.Mime.isVideo(mimetype)) {

                        AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                            public void run() {

                                if (mIsDestroyed)
                                    return;
                                mRequest = null;

                                try {
                                    final RelativeLayout layout = new RelativeLayout(context);
                                    layout.setGravity(Gravity.CENTER);

                                    final VideoView videoView = new VideoView(ImageViewActivity.this);

                                    videoView.setVideoURI(cacheFile.getUri());
                                    layout.addView(videoView);
                                    setContentView(layout);

                                    layout.getLayoutParams().width = ViewGroup.LayoutParams.MATCH_PARENT;
                                    layout.getLayoutParams().height = ViewGroup.LayoutParams.MATCH_PARENT;
                                    videoView.setLayoutParams(
                                            new RelativeLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                                                    ViewGroup.LayoutParams.MATCH_PARENT));

                                    videoView.setOnPreparedListener(new MediaPlayer.OnPreparedListener() {
                                        @Override
                                        public void onPrepared(MediaPlayer mp) {
                                            mp.setLooping(true);
                                            videoView.start();
                                        }
                                    });

                                    videoView.setOnErrorListener(new MediaPlayer.OnErrorListener() {
                                        @Override
                                        public boolean onError(final MediaPlayer mediaPlayer, final int i,
                                                final int i1) {
                                            revertToWeb();
                                            return true;
                                        }
                                    });

                                    videoView.setOnTouchListener(new View.OnTouchListener() {
                                        @Override
                                        public boolean onTouch(final View view, final MotionEvent motionEvent) {
                                            finish();
                                            return true;
                                        }
                                    });

                                } catch (OutOfMemoryError e) {
                                    General.quickToast(context, R.string.imageview_oom);
                                    revertToWeb();

                                } catch (Throwable e) {
                                    General.quickToast(context, R.string.imageview_invalid_video);
                                    revertToWeb();
                                }
                            }
                        });

                    } else if (Constants.Mime.isImageGif(mimetype)) {

                        final PrefsUtility.GifViewMode gifViewMode = PrefsUtility
                                .pref_behaviour_gifview_mode(context, sharedPreferences);

                        if (gifViewMode == PrefsUtility.GifViewMode.INTERNAL_BROWSER) {
                            revertToWeb();
                            return;

                        } else if (gifViewMode == PrefsUtility.GifViewMode.EXTERNAL_BROWSER) {
                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                @Override
                                public void run() {
                                    LinkHandler.openWebBrowser(ImageViewActivity.this,
                                            Uri.parse(mUrl.toString()));
                                    finish();
                                }
                            });

                            return;
                        }

                        if (AndroidApi.isIceCreamSandwichOrLater()
                                && gifViewMode == PrefsUtility.GifViewMode.INTERNAL_MOVIE) {

                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                public void run() {

                                    if (mIsDestroyed)
                                        return;
                                    mRequest = null;

                                    try {
                                        final GIFView gifView = new GIFView(ImageViewActivity.this,
                                                cacheFileInputStream);
                                        setContentView(gifView);
                                        gifView.setOnClickListener(new View.OnClickListener() {
                                            public void onClick(View v) {
                                                finish();
                                            }
                                        });

                                    } catch (OutOfMemoryError e) {
                                        General.quickToast(context, R.string.imageview_oom);
                                        revertToWeb();

                                    } catch (Throwable e) {
                                        General.quickToast(context, R.string.imageview_invalid_gif);
                                        revertToWeb();
                                    }
                                }
                            });

                        } else {

                            gifThread = new GifDecoderThread(cacheFileInputStream,
                                    new GifDecoderThread.OnGifLoadedListener() {

                                        public void onGifLoaded() {
                                            AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                                                public void run() {

                                                    if (mIsDestroyed)
                                                        return;
                                                    mRequest = null;

                                                    imageView = new ImageView(context);
                                                    imageView.setScaleType(ImageView.ScaleType.FIT_CENTER);
                                                    setContentView(imageView);
                                                    gifThread.setView(imageView);

                                                    imageView.setOnClickListener(new View.OnClickListener() {
                                                        public void onClick(View v) {
                                                            finish();
                                                        }
                                                    });
                                                }
                                            });
                                        }

                                        public void onOutOfMemory() {
                                            General.quickToast(context, R.string.imageview_oom);
                                            revertToWeb();
                                        }

                                        public void onGifInvalid() {
                                            General.quickToast(context, R.string.imageview_invalid_gif);
                                            revertToWeb();
                                        }
                                    });

                            gifThread.start();

                        }

                    } else {

                        final ImageTileSource imageTileSource;
                        try {

                            final long bytes = cacheFile.getSize();
                            final byte[] buf = new byte[(int) bytes];

                            try {
                                new DataInputStream(cacheFileInputStream).readFully(buf);
                            } catch (IOException e) {
                                throw new RuntimeException(e);
                            }

                            try {
                                imageTileSource = new ImageTileSourceWholeBitmap(buf);

                            } catch (Throwable t) {
                                Log.e("ImageViewActivity", "Exception when creating ImageTileSource", t);
                                General.quickToast(context, R.string.imageview_decode_failed);
                                revertToWeb();
                                return;
                            }

                        } catch (OutOfMemoryError e) {
                            General.quickToast(context, R.string.imageview_oom);
                            revertToWeb();
                            return;
                        }

                        AndroidApi.UI_THREAD_HANDLER.post(new Runnable() {
                            public void run() {

                                if (mIsDestroyed)
                                    return;
                                mRequest = null;
                                mImageViewDisplayerManager = new ImageViewDisplayListManager(imageTileSource,
                                        ImageViewActivity.this);
                                surfaceView = new RRGLSurfaceView(ImageViewActivity.this,
                                        mImageViewDisplayerManager);
                                setContentView(surfaceView);

                                surfaceView.setOnClickListener(new View.OnClickListener() {
                                    public void onClick(View v) {
                                        finish();
                                    }
                                });

                                if (mIsPaused) {
                                    surfaceView.onPause();
                                } else {
                                    surfaceView.onResume();
                                }
                            }
                        });
                    }
                }
            });

    final RedditPreparedPost post = src_post == null ? null
            : new RedditPreparedPost(this, CacheManager.getInstance(this), 0, src_post, -1, false, false, false,
                    false, RedditAccountManager.getInstance(this).getDefaultAccount(), false);

    final FrameLayout outerFrame = new FrameLayout(this);
    outerFrame.addView(layout);

    if (post != null) {

        final SideToolbarOverlay toolbarOverlay = new SideToolbarOverlay(this);

        final BezelSwipeOverlay bezelOverlay = new BezelSwipeOverlay(this,
                new BezelSwipeOverlay.BezelSwipeListener() {

                    public boolean onSwipe(BezelSwipeOverlay.SwipeEdge edge) {

                        toolbarOverlay.setContents(
                                post.generateToolbar(ImageViewActivity.this, false, toolbarOverlay));
                        toolbarOverlay.show(edge == BezelSwipeOverlay.SwipeEdge.LEFT
                                ? SideToolbarOverlay.SideToolbarPosition.LEFT
                                : SideToolbarOverlay.SideToolbarPosition.RIGHT);
                        return true;
                    }

                    public boolean onTap() {

                        if (toolbarOverlay.isShown()) {
                            toolbarOverlay.hide();
                            return true;
                        }

                        return false;
                    }
                });

        outerFrame.addView(bezelOverlay);
        outerFrame.addView(toolbarOverlay);

        bezelOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        bezelOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

        toolbarOverlay.getLayoutParams().width = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;
        toolbarOverlay.getLayoutParams().height = android.widget.FrameLayout.LayoutParams.MATCH_PARENT;

    }

    setContentView(outerFrame);
}

From source file:com.npi.muzeiflickr.ui.activities.SettingsActivity.java

private void populateFooter(View footerView) {
    final View footerButton = footerView.findViewById(R.id.list_footer_button);
    final Spinner footerModeChooser = (Spinner) footerView.findViewById(R.id.mode_chooser);
    final RelativeLayout addItemContainer = (RelativeLayout) footerView.findViewById(R.id.new_item_container);
    final ImageButton footerSearchButton = (ImageButton) footerView.findViewById(R.id.footer_search_button);
    final ProgressBar footerProgress = (ProgressBar) footerView.findViewById(R.id.footer_progress);
    final EditText footerTerm = (EditText) footerView.findViewById(R.id.footer_term);

    footerButton.setOnLongClickListener(new View.OnLongClickListener() {
        @Override/*  w  ww  .  j  a  v a2s.com*/
        public boolean onLongClick(View v) {
            int[] pos = new int[2];
            footerButton.getLocationInWindow(pos);

            String contentDesc = footerButton.getContentDescription().toString();
            Toast t = Toast.makeText(SettingsActivity.this, contentDesc, Toast.LENGTH_SHORT);
            t.show();
            t.setGravity(Gravity.TOP | Gravity.CENTER_HORIZONTAL, 0, pos[1] + (footerButton.getHeight() / 2));

            return true;
        }
    });

    footerButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            addItemContainer.animate().alpha(1F);
            footerButton.animate().alpha(0F);
        }
    });

    //Mode spinner management
    ArrayAdapter<CharSequence> adapter = new SourceSpinnerAdapter(this, android.R.layout.simple_spinner_item,
            getResources().getStringArray(R.array.modes));

    footerModeChooser.setAdapter(adapter);

    footerSearchButton.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            String searchString = footerTerm.getText().toString();
            switch (footerModeChooser.getSelectedItemPosition()) {
            case 0:

                //It's a search

                //Looking for a same existing search
                List<Search> searchs = Search.listAll(Search.class);
                for (Search search : searchs) {
                    if (search.getTitle().equals(searchString)) {
                        Toast.makeText(SettingsActivity.this, getString(R.string.search_exists),
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                footerSearchButton.setVisibility(View.GONE);
                footerProgress.setVisibility(View.VISIBLE);

                getSearch(searchString, new UserInfoListener<Search>() {
                    @Override
                    public void onSuccess(Search search) {
                        mRequestAdapter.add(search);
                        mRequestAdapter.notifyDataSetChanged();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                        footerTerm.setText("");
                        footerModeChooser.setSelection(0);
                        addItemContainer.animate().alpha(0F);
                        footerButton.animate().alpha(1F);
                    }

                    @Override
                    public void onError(String reason) {
                        Toast.makeText(SettingsActivity.this, reason, Toast.LENGTH_LONG).show();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                    }
                });

                break;
            case 1:
                //It's an user

                //Looking for a same existing search
                List<User> users = User.listAll(User.class);
                for (User user : users) {
                    if (user.getTitle().equals(searchString)) {
                        Toast.makeText(SettingsActivity.this, getString(R.string.user_exists),
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                footerSearchButton.setVisibility(View.GONE);
                footerProgress.setVisibility(View.VISIBLE);

                getUserId(searchString, new UserInfoListener<User>() {
                    @Override
                    public void onSuccess(User user) {
                        mRequestAdapter.add(user);
                        mRequestAdapter.notifyDataSetChanged();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                        footerTerm.setText("");
                        footerModeChooser.setSelection(0);
                        addItemContainer.animate().alpha(0F);
                        footerButton.animate().alpha(1F);
                    }

                    @Override
                    public void onError(String reason) {
                        Toast.makeText(SettingsActivity.this, reason, Toast.LENGTH_LONG).show();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                    }
                });
                break;
            case 2:
                //It's a tag

                //Looking for a same existing search
                List<Tag> tags = Tag.listAll(Tag.class);
                for (Tag tag : tags) {
                    if (tag.getTitle().equals(searchString)) {
                        Toast.makeText(SettingsActivity.this, getString(R.string.user_exists),
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                footerSearchButton.setVisibility(View.GONE);
                footerProgress.setVisibility(View.VISIBLE);

                getTag(searchString, new UserInfoListener<Tag>() {
                    @Override
                    public void onSuccess(Tag tag) {
                        mRequestAdapter.add(tag);
                        mRequestAdapter.notifyDataSetChanged();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                        footerTerm.setText("");
                        footerModeChooser.setSelection(0);
                        addItemContainer.animate().alpha(0F);
                        footerButton.animate().alpha(1F);
                    }

                    @Override
                    public void onError(String reason) {
                        Toast.makeText(SettingsActivity.this, reason, Toast.LENGTH_LONG).show();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                    }
                });
                break;

            case 3:
                //It's an user

                //Looking for a same existing search
                List<FGroup> groups = FGroup.listAll(FGroup.class);
                for (FGroup group : groups) {
                    if (group.getTitle().equals(searchString)) {
                        Toast.makeText(SettingsActivity.this, getString(R.string.group_exists),
                                Toast.LENGTH_LONG).show();
                        return;
                    }
                }

                footerSearchButton.setVisibility(View.GONE);
                footerProgress.setVisibility(View.VISIBLE);

                getGroupId(searchString, new UserInfoListener<FGroup>() {
                    @Override
                    public void onSuccess(FGroup group) {
                        mRequestAdapter.add(group);
                        mRequestAdapter.notifyDataSetChanged();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                        footerTerm.setText("");
                        footerModeChooser.setSelection(0);
                        addItemContainer.animate().alpha(0F);
                        footerButton.animate().alpha(1F);
                    }

                    @Override
                    public void onError(String reason) {
                        Toast.makeText(SettingsActivity.this, reason, Toast.LENGTH_LONG).show();
                        footerSearchButton.setVisibility(View.VISIBLE);
                        footerProgress.setVisibility(View.GONE);
                    }
                });
                break;
            }
        }
    });
}

From source file:com.cw.litenote.note.Note_adapter.java

private void setWebView(final CustomWebView webView, Object object, int whichView) {
    final SharedPreferences pref_web_view = act.getSharedPreferences("web_view", 0);
    final ProgressBar spinner = (ProgressBar) ((View) object).findViewById(R.id.loading);
    if (whichView == CustomWebView.TEXT_VIEW) {
        int scale = pref_web_view.getInt("KEY_WEB_VIEW_SCALE", 0);
        webView.setInitialScale(scale);/*from   w ww.  java 2 s.  c  om*/
    } else if (whichView == CustomWebView.LINK_VIEW) {
        bWebViewIsShown = false;
        webView.setInitialScale(30);
    }

    int style = Note.getStyle();
    webView.setBackgroundColor(ColorSet.mBG_ColorArray[style]);

    webView.getSettings().setBuiltInZoomControls(true);
    webView.getSettings().setSupportZoom(true);
    webView.getSettings().setUseWideViewPort(true);
    //       customWebView.getSettings().setLoadWithOverviewMode(true);
    webView.getSettings().setJavaScriptEnabled(true);//warning: Using setJavaScriptEnabled can introduce XSS vulnerabilities

    //      // speed up
    //      if (Build.VERSION.SDK_INT >= 19) {
    //         // chromium, enable hardware acceleration
    //         webView.setLayerType(View.LAYER_TYPE_HARDWARE, null);
    //      } else {
    //         // older android version, disable hardware acceleration
    //         webView.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    //      }

    if (whichView == CustomWebView.TEXT_VIEW) {
        webView.setWebViewClient(new WebViewClient() {
            @Override
            public void onScaleChanged(WebView web_view, float oldScale, float newScale) {
                super.onScaleChanged(web_view, oldScale, newScale);
                //                System.out.println("Note_adapter / onScaleChanged");
                //                System.out.println("    oldScale = " + oldScale);
                //                System.out.println("    newScale = " + newScale);

                int newDefaultScale = (int) (newScale * 100);
                pref_web_view.edit().putInt("KEY_WEB_VIEW_SCALE", newDefaultScale).apply();

                //update current position
                NoteUi.setFocus_notePos(pager.getCurrentItem());
            }

            @Override
            public void onPageFinished(WebView view, String url) {
            }
        });

    }

    if (whichView == CustomWebView.LINK_VIEW) {
        webView.setWebChromeClient(new WebChromeClient() {
            public void onProgressChanged(WebView view, int progress) {
                System.out.println("---------------- spinner progress = " + progress);

                if (spinner != null) {
                    if (bWebViewIsShown) {
                        if (progress < 100 && (spinner.getVisibility() == ProgressBar.GONE)) {
                            webView.setVisibility(View.GONE);
                            spinner.setVisibility(ProgressBar.VISIBLE);
                        }

                        spinner.setProgress(progress);

                        if (progress > 30)
                            bWebViewIsShown = true;
                    }

                    if (bWebViewIsShown || (progress == 100)) {
                        spinner.setVisibility(ProgressBar.GONE);
                        webView.setVisibility(View.VISIBLE);
                    }
                }
            }

            @Override
            public void onReceivedTitle(WebView view, String title) {
                super.onReceivedTitle(view, title);
                if (!TextUtils.isEmpty(title) && !title.equalsIgnoreCase("about:blank")) {
                    System.out.println("Note_adapter / _onReceivedTitle / title = " + title);

                    int position = NoteUi.getFocus_notePos();
                    String tag = "current" + position + "textWebView";
                    CustomWebView textWebView = (CustomWebView) pager.findViewWithTag(tag);

                    String strLink = db_page.getNoteLinkUri(position, true);

                    // show title of http link
                    if ((textWebView != null) && !Util.isYouTubeLink(strLink) && strLink.startsWith("http")) {
                        mWebTitle = title;
                        showTextWebView(position, textWebView);
                    }
                }
            }
        });
    }
}

From source file:com.aimfire.demo.CamcorderActivity.java

/**
 * recording has been stopped. re-enable control and view3D buttons
 *///from   w  ww . ja  v a2 s  .c  o m
@SuppressWarnings("unused")
private void setControlRecordingOff() {
    /*
     * capture is finished, re-enable buttons
     */
    mPvButton.setEnabled(true);
    //mFbButton.setEnabled(true);

    /*
     * view3D button not enabled until processing of new video is done
     */
    mView3DButton.setEnabled(false);

    ProgressBar pb = (ProgressBar) findViewById(R.id.view3D_progress_bar);
    pb.setVisibility(View.VISIBLE);

    if (MainConsts.VIDEO_LENGTH_SECONDS == -1) {
        /*
         * display time counter only if indeterminate recording
         */
        mTimeCounter.setVisibility(View.INVISIBLE);
    }
}

From source file:biz.bokhorst.xprivacy.ActivityMain.java

private void applyFilter() {
    if (mAppAdapter != null) {
        ProgressBar pbFilter = (ProgressBar) findViewById(R.id.pbFilter);
        TextView tvStats = (TextView) findViewById(R.id.tvStats);
        TextView tvState = (TextView) findViewById(R.id.tvState);

        // Get settings
        int userId = Util.getUserId(Process.myUid());
        boolean fUsed = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUsed, false);
        boolean fInternet = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFInternet, false);
        boolean fRestriction = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestriction,
                false);/*from  w  ww .j  a  v  a2 s  .com*/
        boolean fRestrictionNot = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFRestrictionNot,
                false);
        boolean fPermission = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFPermission, true);
        boolean fOnDemand = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemand, false);
        boolean fOnDemandNot = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFOnDemandNot,
                false);
        boolean fUser = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFUser, true);
        boolean fSystem = PrivacyManager.getSettingBool(userId, PrivacyManager.cSettingFSystem, false);

        String filter = String.format("%s\n%b\n%b\n%b\n%b\n%b\n%b\n%b\n%b\n%b", searchQuery, fUsed, fInternet,
                fRestriction, fRestrictionNot, fPermission, fOnDemand, fOnDemandNot, fUser, fSystem);
        pbFilter.setVisibility(ProgressBar.VISIBLE);
        tvStats.setVisibility(TextView.GONE);

        // Adjust progress state width
        RelativeLayout.LayoutParams tvStateLayout = (RelativeLayout.LayoutParams) tvState.getLayoutParams();
        tvStateLayout.addRule(RelativeLayout.LEFT_OF, R.id.pbFilter);

        mAppAdapter.getFilter().filter(filter);
    }
}

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(/*from w w w .  j  ava 2s . co  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:at.alladin.rmbt.android.adapter.result.RMBTResultPagerAdapter.java

/**
 * /*from  w w  w  .  ja  v  a  2s.  c  o  m*/
 * @param view
 */
private void displayResult(View view, LayoutInflater inflater, ViewGroup vg) {
    /*
     final Button shareButton = (Button) view.findViewById(R.id.resultButtonShare);
     if (shareButton != null)
    shareButton.setEnabled(false);
    */

    //final LinearLayout measurementLayout = (LinearLayout) view.findViewById(R.id.resultMeasurementList);
    measurementLayout = (LinearLayout) view.findViewById(R.id.resultMeasurementList);
    measurementLayout.setVisibility(View.GONE);

    final LinearLayout resultLayout = (LinearLayout) view.findViewById(R.id.result_layout);
    resultLayout.setVisibility(View.INVISIBLE);

    final LinearLayout netLayout = (LinearLayout) view.findViewById(R.id.resultNetList);
    netLayout.setVisibility(View.GONE);

    final TextView measurementHeader = (TextView) view.findViewById(R.id.resultMeasurement);
    measurementHeader.setVisibility(View.GONE);

    final TextView netHeader = (TextView) view.findViewById(R.id.resultNet);
    netHeader.setVisibility(View.GONE);

    final TextView emptyView = (TextView) view.findViewById(R.id.infoText);
    emptyView.setVisibility(View.GONE);
    final float scale = activity.getResources().getDisplayMetrics().density;

    final ProgressBar progessBar = (ProgressBar) view.findViewById(R.id.progressBar);

    if (testResult != null && testResult.length() > 0) {

        JSONObject resultListItem;

        try {
            resultListItem = testResult.getJSONObject(0);

            openTestUuid = resultListItem.optString("open_test_uuid");
            if (graphView != null) {
                graphView.setOpenTestUuid(openTestUuid);
                graphView.initialize(graphViewEndTaskListener);
            }

            JSONObject testResultItem;
            try {
                testResultItem = testResult.getJSONObject(0);
                if (testResultItem.has("geo_lat") && testResultItem.has("geo_long") && !hasMap) {
                    hasMap = true;
                    if (dataChangedListener != null) {
                        dataChangedListener.onChange(false, true, "HAS_MAP");
                    }
                    notifyDataSetChanged();
                } else if (!testResultItem.has("geo_lat") && !testResultItem.has("geo_long") && hasMap) {
                    System.out.println("hasMap = " + hasMap);
                    hasMap = false;
                    if (dataChangedListener != null) {
                        dataChangedListener.onChange(true, false, "HAS_MAP");
                    }
                    notifyDataSetChanged();
                }
            } catch (JSONException e) {
                hasMap = false;
                e.printStackTrace();
            }

            if (completeListener != null) {
                completeListener.onComplete(OnCompleteListener.DATA_LOADED, this);
            }

            final JSONArray measurementArray = resultListItem.getJSONArray("measurement");

            final JSONArray netArray = resultListItem.getJSONArray("net");

            final int leftRightDiv = Helperfunctions.dpToPx(0, scale);
            final int topBottomDiv = Helperfunctions.dpToPx(0, scale);
            final int heightDiv = Helperfunctions.dpToPx(1, scale);

            for (int i = 0; i < measurementArray.length(); i++) {

                final View measurementItemView = inflater.inflate(R.layout.classification_list_item, vg, false);

                final JSONObject singleItem = measurementArray.getJSONObject(i);

                final TextView itemTitle = (TextView) measurementItemView
                        .findViewById(R.id.classification_item_title);
                itemTitle.setText(singleItem.getString("title"));

                final ImageView itemClassification = (ImageView) measurementItemView
                        .findViewById(R.id.classification_item_color);
                itemClassification.setImageResource(
                        Helperfunctions.getClassificationColor(singleItem.getInt("classification")));

                itemClassification.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        activity.showHelp(R.string.url_help_result, false);
                    }
                });

                final TextView itemValue = (TextView) measurementItemView
                        .findViewById(R.id.classification_item_value);
                itemValue.setText(singleItem.getString("value"));

                measurementLayout.addView(measurementItemView);

                final View divider = new View(activity);
                divider.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, heightDiv, 1));
                divider.setPadding(leftRightDiv, topBottomDiv, leftRightDiv, topBottomDiv);

                divider.setBackgroundResource(R.drawable.bg_trans_light_10);

                measurementLayout.addView(divider);

                measurementLayout.invalidate();
            }

            for (int i = 0; i < netArray.length(); i++) {

                final JSONObject singleItem = netArray.getJSONObject(i);

                addResultListItem(singleItem.getString("title"), singleItem.optString("value", null),
                        netLayout);
            }

            addQoSResultItem();

        } catch (final JSONException e) {
            e.printStackTrace();
        }

        progessBar.setVisibility(View.GONE);
        emptyView.setVisibility(View.GONE);

        resultLayout.setVisibility(View.VISIBLE);
        measurementHeader.setVisibility(View.VISIBLE);
        netHeader.setVisibility(View.VISIBLE);

        measurementLayout.setVisibility(View.VISIBLE);
        netLayout.setVisibility(View.VISIBLE);

    } else {
        Log.i(DEBUG_TAG, "LEERE LISTE");
        progessBar.setVisibility(View.GONE);
        emptyView.setVisibility(View.VISIBLE);
        emptyView.setText(activity.getString(R.string.error_no_data));
        emptyView.invalidate();
    }
}