Example usage for android.widget ImageView setContentDescription

List of usage examples for android.widget ImageView setContentDescription

Introduction

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

Prototype

@RemotableViewMethod
public void setContentDescription(CharSequence contentDescription) 

Source Link

Document

Sets the View 's content description.

Usage

From source file:com.google.samples.apps.iosched.session.SessionDetailFragment.java

private void displaySpeakersData(SessionDetailModel data) {
    final ViewGroup speakersGroup = (ViewGroup) getActivity().findViewById(R.id.session_speakers_block);

    // Remove all existing speakers (everything but first child, which is the header)
    for (int i = speakersGroup.getChildCount() - 1; i >= 1; i--) {
        speakersGroup.removeViewAt(i);//from ww  w .ja va2 s. co m
    }

    final LayoutInflater inflater = getActivity().getLayoutInflater();

    boolean hasSpeakers = false;

    List<SessionDetailModel.Speaker> speakers = data.getSpeakers();

    for (final SessionDetailModel.Speaker speaker : speakers) {

        String speakerHeader = speaker.getName();
        if (!TextUtils.isEmpty(speaker.getCompany())) {
            speakerHeader += ", " + speaker.getCompany();
        }

        final View speakerView = inflater.inflate(R.layout.speaker_detail, speakersGroup, false);
        final TextView speakerHeaderView = (TextView) speakerView.findViewById(R.id.speaker_header);
        final ImageView speakerImageView = (ImageView) speakerView.findViewById(R.id.speaker_image);
        final TextView speakerAbstractView = (TextView) speakerView.findViewById(R.id.speaker_abstract);
        final ImageView plusOneIcon = (ImageView) speakerView.findViewById(R.id.gplus_icon_box);
        final ImageView twitterIcon = (ImageView) speakerView.findViewById(R.id.twitter_icon_box);

        setUpSpeakerSocialIcon(speaker, twitterIcon, speaker.getTwitterUrl(), UIUtils.TWITTER_COMMON_NAME,
                UIUtils.TWITTER_PACKAGE_NAME);

        setUpSpeakerSocialIcon(speaker, plusOneIcon, speaker.getPlusoneUrl(), UIUtils.GOOGLE_PLUS_COMMON_NAME,
                UIUtils.GOOGLE_PLUS_PACKAGE_NAME);

        // A speaker may have both a Twitter and GPlus page, only a Twitter page or only a
        // GPlus page, or neither. By default, align the Twitter icon to the right and the GPlus
        // icon to its left. If only a single icon is displayed, align it to the right.
        determineSocialIconPlacement(plusOneIcon, twitterIcon);

        if (!TextUtils.isEmpty(speaker.getImageUrl()) && mSpeakersImageLoader != null) {
            mSpeakersImageLoader.loadImage(speaker.getImageUrl(), speakerImageView);
        }

        speakerHeaderView.setText(speakerHeader);
        speakerImageView.setContentDescription(getString(R.string.speaker_googleplus_profile, speakerHeader));
        UIUtils.setTextMaybeHtml(speakerAbstractView, speaker.getAbstract());

        if (!TextUtils.isEmpty(speaker.getUrl())) {
            speakerImageView.setEnabled(true);
            speakerImageView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View view) {
                    Intent speakerProfileIntent = new Intent(Intent.ACTION_VIEW, Uri.parse(speaker.getUrl()));
                    speakerProfileIntent.addFlags(Intent.FLAG_ACTIVITY_CLEAR_WHEN_TASK_RESET);
                    UIUtils.preferPackageForIntent(getActivity(), speakerProfileIntent,
                            UIUtils.GOOGLE_PLUS_PACKAGE_NAME);
                    startActivity(speakerProfileIntent);
                }
            });
        } else {
            speakerImageView.setEnabled(false);
            speakerImageView.setOnClickListener(null);
        }

        speakersGroup.addView(speakerView);
        hasSpeakers = true;
    }

    speakersGroup.setVisibility(hasSpeakers ? View.VISIBLE : View.GONE);
    updateEmptyView(data);
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

private void addMediaToQueue(@Nullable String id, QueuedMedia.Type type, Bitmap preview, Uri uri,
        long mediaSize, QueuedMedia.ReadyStage readyStage, @Nullable String description) {
    final QueuedMedia item = new QueuedMedia(type, uri, new ProgressImageView(this), mediaSize, description);
    item.id = id;// w w w .ja  v a2  s.  c o  m
    item.readyStage = readyStage;
    ImageView view = item.preview;
    Resources resources = getResources();
    int margin = resources.getDimensionPixelSize(R.dimen.compose_media_preview_margin);
    int marginBottom = resources.getDimensionPixelSize(R.dimen.compose_media_preview_margin_bottom);
    LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(thumbnailViewSize,
            thumbnailViewSize);
    layoutParams.setMargins(margin, 0, margin, marginBottom);
    view.setLayoutParams(layoutParams);
    view.setScaleType(ImageView.ScaleType.CENTER_CROP);
    view.setImageBitmap(preview);
    view.setOnClickListener(v -> onMediaClick(item, v));
    view.setContentDescription(getString(R.string.action_delete));
    mediaPreviewBar.addView(view);
    mediaQueued.add(item);
    int queuedCount = mediaQueued.size();
    if (queuedCount == 1) {
        // If there's one video in the queue it is full, so disable the button to queue more.
        if (item.type == QueuedMedia.Type.VIDEO) {
            enableButton(pickButton, false, false);
        }
    } else if (queuedCount >= Status.MAX_MEDIA_ATTACHMENTS) {
        // Limit the total media attachments, also.
        enableButton(pickButton, false, false);
    }

    updateHideMediaToggle();

    if (item.readyStage != QueuedMedia.ReadyStage.UPLOADED) {
        waitForMediaLatch.countUp();

        try {
            if (type == QueuedMedia.Type.IMAGE && (mediaSize > STATUS_MEDIA_SIZE_LIMIT || MediaUtils
                    .getImageSquarePixels(getContentResolver(), item.uri) > STATUS_MEDIA_PIXEL_SIZE_LIMIT)) {
                downsizeMedia(item);
            } else {
                uploadMedia(item);
            }
        } catch (FileNotFoundException e) {
            onUploadFailure(item, false);
        }
    }
}

From source file:com.keylesspalace.tusky.ComposeActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    SharedPreferences preferences = PreferenceManager.getDefaultSharedPreferences(this);
    String theme = preferences.getString("appTheme", ThemeUtils.APP_THEME_DEFAULT);
    if (theme.equals("black")) {
        setTheme(R.style.TuskyDialogActivityBlackTheme);
    }/* w  ww .j a  v  a 2 s .co m*/
    setContentView(R.layout.activity_compose);

    replyTextView = findViewById(R.id.composeReplyView);
    replyContentTextView = findViewById(R.id.composeReplyContentView);
    textEditor = findViewById(R.id.composeEditField);
    mediaPreviewBar = findViewById(R.id.compose_media_preview_bar);
    contentWarningBar = findViewById(R.id.composeContentWarningBar);
    contentWarningEditor = findViewById(R.id.composeContentWarningField);
    charactersLeft = findViewById(R.id.composeCharactersLeftView);
    tootButton = findViewById(R.id.composeTootButton);
    pickButton = findViewById(R.id.composeAddMediaButton);
    visibilityButton = findViewById(R.id.composeToggleVisibilityButton);
    contentWarningButton = findViewById(R.id.composeContentWarningButton);
    emojiButton = findViewById(R.id.composeEmojiButton);
    hideMediaToggle = findViewById(R.id.composeHideMediaButton);
    emojiView = findViewById(R.id.emojiView);
    emojiList = Collections.emptyList();

    saveTootHelper = new SaveTootHelper(database.tootDao(), this);

    // Setup the toolbar.
    Toolbar toolbar = findViewById(R.id.toolbar);
    setSupportActionBar(toolbar);
    ActionBar actionBar = getSupportActionBar();
    if (actionBar != null) {
        actionBar.setTitle(null);
        actionBar.setDisplayHomeAsUpEnabled(true);
        actionBar.setDisplayShowHomeEnabled(true);
        Drawable closeIcon = AppCompatResources.getDrawable(this, R.drawable.ic_close_24dp);
        ThemeUtils.setDrawableTint(this, closeIcon, R.attr.compose_close_button_tint);
        actionBar.setHomeAsUpIndicator(closeIcon);
    }

    // setup the account image
    final AccountEntity activeAccount = accountManager.getActiveAccount();

    if (activeAccount != null) {
        ImageView composeAvatar = findViewById(R.id.composeAvatar);

        if (TextUtils.isEmpty(activeAccount.getProfilePictureUrl())) {
            composeAvatar.setImageResource(R.drawable.avatar_default);
        } else {
            Picasso.with(this).load(activeAccount.getProfilePictureUrl()).error(R.drawable.avatar_default)
                    .placeholder(R.drawable.avatar_default).into(composeAvatar);
        }

        composeAvatar.setContentDescription(
                getString(R.string.compose_active_account_description, activeAccount.getFullName()));

        mastodonApi.getInstance().enqueue(new Callback<Instance>() {
            @Override
            public void onResponse(@NonNull Call<Instance> call, @NonNull Response<Instance> response) {
                if (response.isSuccessful() && response.body().getMaxTootChars() != null) {
                    maximumTootCharacters = response.body().getMaxTootChars();
                    updateVisibleCharactersLeft();
                    cacheInstanceMetadata(activeAccount);
                }
            }

            @Override
            public void onFailure(@NonNull Call<Instance> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading instance data", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });

        mastodonApi.getCustomEmojis().enqueue(new Callback<List<Emoji>>() {
            @Override
            public void onResponse(@NonNull Call<List<Emoji>> call, @NonNull Response<List<Emoji>> response) {
                emojiList = response.body();
                setEmojiList(emojiList);
                cacheInstanceMetadata(activeAccount);
            }

            @Override
            public void onFailure(@NonNull Call<List<Emoji>> call, @NonNull Throwable t) {
                Log.w(TAG, "error loading custom emojis", t);
                loadCachedInstanceMetadata(activeAccount);
            }
        });
    } else {
        // do not do anything when not logged in, activity will be finished in super.onCreate() anyway
        return;
    }

    composeOptionsView = findViewById(R.id.composeOptionsBottomSheet);
    composeOptionsView.setListener(this);

    composeOptionsBehavior = BottomSheetBehavior.from(composeOptionsView);
    composeOptionsBehavior.setState(BottomSheetBehavior.STATE_HIDDEN);

    addMediaBehavior = BottomSheetBehavior.from(findViewById(R.id.addMediaBottomSheet));

    emojiBehavior = BottomSheetBehavior.from(emojiView);

    emojiView.setLayoutManager(new GridLayoutManager(this, 3, GridLayoutManager.HORIZONTAL, false));

    enableButton(emojiButton, false, false);

    // Setup the interface buttons.
    tootButton.setOnClickListener(v -> onSendClicked());
    pickButton.setOnClickListener(v -> openPickDialog());
    visibilityButton.setOnClickListener(v -> showComposeOptions());
    contentWarningButton.setOnClickListener(v -> onContentWarningChanged());
    emojiButton.setOnClickListener(v -> showEmojis());
    hideMediaToggle.setOnClickListener(v -> toggleHideMedia());

    TextView actionPhotoTake = findViewById(R.id.action_photo_take);
    TextView actionPhotoPick = findViewById(R.id.action_photo_pick);

    int textColor = ThemeUtils.getColor(this, android.R.attr.textColorTertiary);

    Drawable cameraIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_camera_alt).color(textColor)
            .sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoTake, cameraIcon, null, null,
            null);

    Drawable imageIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_image).color(textColor).sizeDp(18);
    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(actionPhotoPick, imageIcon, null, null,
            null);

    actionPhotoTake.setOnClickListener(v -> initiateCameraApp());
    actionPhotoPick.setOnClickListener(v -> onMediaPick());

    thumbnailViewSize = getResources().getDimensionPixelSize(R.dimen.compose_media_preview_size);

    /* Initialise all the state, or restore it from a previous run, to determine a "starting"
     * state. */
    Status.Visibility startingVisibility = Status.Visibility.UNKNOWN;
    boolean startingHideText;
    ArrayList<SavedQueuedMedia> savedMediaQueued = null;
    if (savedInstanceState != null) {
        startingVisibility = Status.Visibility
                .byNum(savedInstanceState.getInt("statusVisibility", Status.Visibility.PUBLIC.getNum()));
        statusMarkSensitive = savedInstanceState.getBoolean("statusMarkSensitive");
        startingHideText = savedInstanceState.getBoolean("statusHideText");
        // Keep these until everything needed to put them in the queue is finished initializing.
        savedMediaQueued = savedInstanceState.getParcelableArrayList("savedMediaQueued");
        // These are for restoring an in-progress commit content operation.
        InputContentInfoCompat previousInputContentInfo = InputContentInfoCompat
                .wrap(savedInstanceState.getParcelable("commitContentInputContentInfo"));
        int previousFlags = savedInstanceState.getInt("commitContentFlags");
        if (previousInputContentInfo != null) {
            onCommitContentInternal(previousInputContentInfo, previousFlags);
        }
        photoUploadUri = savedInstanceState.getParcelable("photoUploadUri");
    } else {
        statusMarkSensitive = false;
        startingHideText = false;
        photoUploadUri = null;
    }

    /* If the composer is started up as a reply to another post, override the "starting" state
     * based on what the intent from the reply request passes. */
    Intent intent = getIntent();

    String[] mentionedUsernames = null;
    ArrayList<String> loadedDraftMediaUris = null;
    inReplyToId = null;
    if (intent != null) {

        if (startingVisibility == Status.Visibility.UNKNOWN) {
            Status.Visibility preferredVisibility = Status.Visibility.byString(
                    preferences.getString("defaultPostPrivacy", Status.Visibility.PUBLIC.serverString()));
            Status.Visibility replyVisibility = Status.Visibility
                    .byNum(intent.getIntExtra(REPLY_VISIBILITY_EXTRA, Status.Visibility.UNKNOWN.getNum()));

            startingVisibility = Status.Visibility
                    .byNum(Math.max(preferredVisibility.getNum(), replyVisibility.getNum()));
        }

        inReplyToId = intent.getStringExtra(IN_REPLY_TO_ID_EXTRA);

        mentionedUsernames = intent.getStringArrayExtra(MENTIONED_USERNAMES_EXTRA);

        String contentWarning = intent.getStringExtra(CONTENT_WARNING_EXTRA);
        if (contentWarning != null) {
            startingHideText = !contentWarning.isEmpty();
            if (startingHideText) {
                startingContentWarning = contentWarning;
            }
        }

        // If come from SavedTootActivity
        String savedTootText = intent.getStringExtra(SAVED_TOOT_TEXT_EXTRA);
        if (!TextUtils.isEmpty(savedTootText)) {
            startingText = savedTootText;
            textEditor.setText(savedTootText);
        }

        String savedJsonUrls = intent.getStringExtra(SAVED_JSON_URLS_EXTRA);
        if (!TextUtils.isEmpty(savedJsonUrls)) {
            // try to redo a list of media
            loadedDraftMediaUris = new Gson().fromJson(savedJsonUrls, new TypeToken<ArrayList<String>>() {
            }.getType());
        }

        int savedTootUid = intent.getIntExtra(SAVED_TOOT_UID_EXTRA, 0);
        if (savedTootUid != 0) {
            this.savedTootUid = savedTootUid;
        }

        if (intent.hasExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA)) {
            replyTextView.setVisibility(View.VISIBLE);
            String username = intent.getStringExtra(REPLYING_STATUS_AUTHOR_USERNAME_EXTRA);
            replyTextView.setText(getString(R.string.replying_to, username));
            Drawable arrowDownIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_down)
                    .sizeDp(12);

            ThemeUtils.setDrawableTint(this, arrowDownIcon, android.R.attr.textColorTertiary);
            TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                    arrowDownIcon, null);

            replyTextView.setOnClickListener(v -> {
                TransitionManager.beginDelayedTransition((ViewGroup) replyContentTextView.getParent());

                if (replyContentTextView.getVisibility() != View.VISIBLE) {
                    replyContentTextView.setVisibility(View.VISIBLE);
                    Drawable arrowUpIcon = new IconicsDrawable(this, GoogleMaterial.Icon.gmd_arrow_drop_up)
                            .sizeDp(12);

                    ThemeUtils.setDrawableTint(this, arrowUpIcon, android.R.attr.textColorTertiary);
                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowUpIcon, null);
                } else {
                    replyContentTextView.setVisibility(View.GONE);

                    TextViewCompat.setCompoundDrawablesRelativeWithIntrinsicBounds(replyTextView, null, null,
                            arrowDownIcon, null);
                }
            });
        }

        if (intent.hasExtra(REPLYING_STATUS_CONTENT_EXTRA)) {
            replyContentTextView.setText(intent.getStringExtra(REPLYING_STATUS_CONTENT_EXTRA));
        }
    }

    // After the starting state is finalised, the interface can be set to reflect this state.
    setStatusVisibility(startingVisibility);

    updateHideMediaToggle();
    updateVisibleCharactersLeft();

    // Setup the main text field.
    textEditor.setOnCommitContentListener(this);
    final int mentionColour = textEditor.getLinkTextColors().getDefaultColor();
    SpanUtilsKt.highlightSpans(textEditor.getText(), mentionColour);
    textEditor.addTextChangedListener(new TextWatcher() {
        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void afterTextChanged(Editable editable) {
            SpanUtilsKt.highlightSpans(editable, mentionColour);
            updateVisibleCharactersLeft();
        }
    });

    textEditor.setAdapter(new MentionAutoCompleteAdapter(this, R.layout.item_autocomplete, this));
    textEditor.setTokenizer(new MentionTokenizer());

    // Add any mentions to the text field when a reply is first composed.
    if (mentionedUsernames != null) {
        StringBuilder builder = new StringBuilder();
        for (String name : mentionedUsernames) {
            builder.append('@');
            builder.append(name);
            builder.append(' ');
        }
        startingText = builder.toString();
        textEditor.setText(startingText);
        textEditor.setSelection(textEditor.length());
    }

    // work around Android platform bug -> https://issuetracker.google.com/issues/67102093
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.O || Build.VERSION.SDK_INT == Build.VERSION_CODES.O_MR1) {
        textEditor.setLayerType(View.LAYER_TYPE_SOFTWARE, null);
    }

    // Initialise the content warning editor.
    contentWarningEditor.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) {
            updateVisibleCharactersLeft();
        }

        @Override
        public void afterTextChanged(Editable s) {
        }
    });
    showContentWarning(startingHideText);
    if (startingContentWarning != null) {
        contentWarningEditor.setText(startingContentWarning);
    }

    // Initialise the empty media queue state.
    waitForMediaLatch = new CountUpDownLatch();

    // These can only be added after everything affected by the media queue is initialized.
    if (!ListUtils.isEmpty(loadedDraftMediaUris)) {
        for (String uriString : loadedDraftMediaUris) {
            Uri uri = Uri.parse(uriString);
            long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
            pickMedia(uri, mediaSize);
        }
    } else if (savedMediaQueued != null) {
        for (SavedQueuedMedia item : savedMediaQueued) {
            Bitmap preview = MediaUtils.getImageThumbnail(getContentResolver(), item.uri, thumbnailViewSize);
            addMediaToQueue(item.id, item.type, preview, item.uri, item.mediaSize, item.readyStage,
                    item.description);
        }
    } else if (intent != null && savedInstanceState == null) {
        /* Get incoming images being sent through a share action from another app. Only do this
         * when savedInstanceState is null, otherwise both the images from the intent and the
         * instance state will be re-queued. */
        String type = intent.getType();
        if (type != null) {
            if (type.startsWith("image/")) {
                List<Uri> uriList = new ArrayList<>();
                if (intent.getAction() != null) {
                    switch (intent.getAction()) {
                    case Intent.ACTION_SEND: {
                        Uri uri = intent.getParcelableExtra(Intent.EXTRA_STREAM);
                        if (uri != null) {
                            uriList.add(uri);
                        }
                        break;
                    }
                    case Intent.ACTION_SEND_MULTIPLE: {
                        ArrayList<Uri> list = intent.getParcelableArrayListExtra(Intent.EXTRA_STREAM);
                        if (list != null) {
                            for (Uri uri : list) {
                                if (uri != null) {
                                    uriList.add(uri);
                                }
                            }
                        }
                        break;
                    }
                    }
                }
                for (Uri uri : uriList) {
                    long mediaSize = MediaUtils.getMediaSize(getContentResolver(), uri);
                    pickMedia(uri, mediaSize);
                }
            } else if (type.equals("text/plain")) {
                String action = intent.getAction();
                if (action != null && action.equals(Intent.ACTION_SEND)) {
                    String text = intent.getStringExtra(Intent.EXTRA_TEXT);
                    if (text != null) {
                        int start = Math.max(textEditor.getSelectionStart(), 0);
                        int end = Math.max(textEditor.getSelectionEnd(), 0);
                        int left = Math.min(start, end);
                        int right = Math.max(start, end);
                        textEditor.getText().replace(left, right, text, 0, text.length());
                    }
                }
            }
        }
    }

    textEditor.requestFocus();
}

From source file:com.google.samples.apps.iosched.ui.BaseActivity.java

/**
 * Sets up the account box. The account box is the area at the top of the nav drawer that
 * shows which account the user is logged in as, and lets them switch accounts. It also
 * shows the user's Google+ cover photo as background.
 *//* w  ww.  j  a v  a  2 s  . c o m*/
private void setupAccountBox() {
    mAccountListContainer = (LinearLayout) findViewById(R.id.account_list);

    if (mAccountListContainer == null) {
        //This activity does not have an account box
        return;
    }

    final View chosenAccountView = findViewById(R.id.chosen_account_view);
    Account chosenAccount = AccountUtils.getActiveAccount(this);
    if (chosenAccount == null) {
        // No account logged in; hide account box
        chosenAccountView.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        return;
    } else {
        chosenAccountView.setVisibility(View.VISIBLE);
        mAccountListContainer.setVisibility(View.INVISIBLE);
    }

    AccountManager am = AccountManager.get(this);
    Account[] accountArray = am.getAccountsByType(GoogleAuthUtil.GOOGLE_ACCOUNT_TYPE);
    List<Account> accounts = new ArrayList<Account>(Arrays.asList(accountArray));
    accounts.remove(chosenAccount);

    ImageView coverImageView = (ImageView) chosenAccountView.findViewById(R.id.profile_cover_image);
    ImageView profileImageView = (ImageView) chosenAccountView.findViewById(R.id.profile_image);
    TextView nameTextView = (TextView) chosenAccountView.findViewById(R.id.profile_name_text);
    TextView email = (TextView) chosenAccountView.findViewById(R.id.profile_email_text);
    mExpandAccountBoxIndicator = (ImageView) findViewById(R.id.expand_account_box_indicator);

    String name = AccountUtils.getPlusName(this);
    if (name == null) {
        nameTextView.setVisibility(View.GONE);
    } else {
        nameTextView.setVisibility(View.VISIBLE);
        nameTextView.setText(name);
    }

    String imageUrl = AccountUtils.getPlusImageUrl(this);
    if (imageUrl != null) {
        mImageLoader.loadImage(imageUrl, profileImageView);
    }

    String coverImageUrl = AccountUtils.getPlusCoverUrl(this);
    if (coverImageUrl != null) {
        findViewById(R.id.profile_cover_image_placeholder).setVisibility(View.GONE);
        coverImageView.setVisibility(View.VISIBLE);
        coverImageView.setContentDescription(
                getResources().getString(R.string.navview_header_user_image_content_description));
        mImageLoader.loadImage(coverImageUrl, coverImageView);
        coverImageView.setColorFilter(getResources().getColor(R.color.light_content_scrim));
    }

    email.setText(chosenAccount.name);

    if (accounts.isEmpty()) {
        // There's only one account on the device, so no need for a switcher.
        mExpandAccountBoxIndicator.setVisibility(View.GONE);
        mAccountListContainer.setVisibility(View.GONE);
        chosenAccountView.setEnabled(false);
        return;
    }

    chosenAccountView.setEnabled(true);

    mExpandAccountBoxIndicator.setVisibility(View.VISIBLE);
    chosenAccountView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            mAccountBoxExpanded = !mAccountBoxExpanded;
            setupAccountBoxToggle();
        }
    });
    setupAccountBoxToggle();

    populateAccountList(accounts);
}

From source file:com.kll.collect.android.activities.FormEntryActivity.java

/**
 * Creates a view given the View type and an event
 *
 * @param event/* w  w  w  .  ja  v  a2 s. co  m*/
 * @param advancingPage
 *            -- true if this results from advancing through the form
 * @return newly created View
 */
private View createView(int event, boolean advancingPage, int swipeCase) {
    FormController formController = Collect.getInstance().getFormController();
    /*   setTitle(getString(R.string.app_name) + " > "
    + formController.getFormTitle());*/
    int questioncount = formController.getFormDef().getDeepChildCount();

    switch (event) {
    case FormEntryController.EVENT_BEGINNING_OF_FORM:
        progressValue = 0.0;
        progressUpdate(progressValue, questioncount);
        View startView = View.inflate(this, R.layout.form_entry_start, null);
        /*setTitle(getString(R.string.app_name) + " > "
              + formController.getFormTitle());*/

        Drawable image = null;
        File mediaFolder = formController.getMediaFolder();
        String mediaDir = mediaFolder.getAbsolutePath();
        BitmapDrawable bitImage = null;
        // attempt to load the form-specific logo...
        // this is arbitrarily silly
        bitImage = new BitmapDrawable(getResources(), mediaDir + File.separator + "form_logo.png");

        if (bitImage != null && bitImage.getBitmap() != null && bitImage.getIntrinsicHeight() > 0
                && bitImage.getIntrinsicWidth() > 0) {
            image = bitImage;
        }

        if (image == null) {
            // show the opendatakit zig...
            // image =
            // getResources().getDrawable(R.drawable.opendatakit_zig);
            ((ImageView) startView.findViewById(R.id.form_start_bling)).setVisibility(View.GONE);
        } else {
            ImageView v = ((ImageView) startView.findViewById(R.id.form_start_bling));
            v.setImageDrawable(image);
            v.setContentDescription(formController.getFormTitle());
        }

        // change start screen based on navigation prefs
        String navigationChoice = PreferenceManager.getDefaultSharedPreferences(this)
                .getString(PreferencesActivity.KEY_NAVIGATION, PreferencesActivity.KEY_NAVIGATION);
        Boolean useSwipe = false;
        Boolean useButtons = false;
        ImageView ia = ((ImageView) startView.findViewById(R.id.image_advance));
        ImageView ib = ((ImageView) startView.findViewById(R.id.image_backup));
        TextView ta = ((TextView) startView.findViewById(R.id.text_advance));
        TextView tb = ((TextView) startView.findViewById(R.id.text_backup));
        TextView d = ((TextView) startView.findViewById(R.id.description));

        if (navigationChoice != null) {
            if (navigationChoice.contains(PreferencesActivity.NAVIGATION_SWIPE)) {
                useSwipe = true;
            }
            if (navigationChoice.contains(PreferencesActivity.NAVIGATION_BUTTONS)) {
                useButtons = true;
            }
        }
        if (useSwipe && !useButtons) {
            d.setText(getString(R.string.swipe_instructions, formController.getFormTitle()));
        } else if (useButtons && !useSwipe) {
            ia.setVisibility(View.GONE);
            ib.setVisibility(View.GONE);
            ta.setVisibility(View.GONE);
            tb.setVisibility(View.GONE);
            d.setText(getString(R.string.buttons_instructions, formController.getFormTitle()));
        } else {
            d.setText(getString(R.string.swipe_buttons_instructions, formController.getFormTitle()));
        }

        if (mBackButton.isShown()) {
            mBackButton.setEnabled(false);
        }
        if (mNextButton.isShown()) {
            mNextButton.setEnabled(true);
        }

        return startView;
    case FormEntryController.EVENT_END_OF_FORM:
        progressValue = questioncount;
        progressUpdate(progressValue, questioncount);
        View endView = View.inflate(this, R.layout.form_entry_end, null);

        ((ImageView) endView.findViewById(R.id.completed))
                .setImageDrawable(getResources().getDrawable(R.drawable.complete_tick));
        ((TextView) endView.findViewById(R.id.description))
                .setText(getString(R.string.save_enter_data_description, formController.getFormTitle()));

        // checkbox for if finished or ready to send
        final CheckBox instanceComplete = ((CheckBox) endView.findViewById(R.id.mark_finished));
        instanceComplete.setChecked(isInstanceComplete(true));

        if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_MARK_AS_FINALIZED, true)) {
            instanceComplete.setVisibility(View.GONE);
        }

        // edittext to change the displayed name of the instance
        final EditText saveAs = (EditText) endView.findViewById(R.id.save_name);

        // disallow carriage returns in the name
        InputFilter returnFilter = new InputFilter() {
            public CharSequence filter(CharSequence source, int start, int end, Spanned dest, int dstart,
                    int dend) {
                for (int i = start; i < end; i++) {
                    if (Character.getType((source.charAt(i))) == Character.CONTROL) {
                        return "";
                    }
                }
                return null;
            }
        };
        saveAs.setFilters(new InputFilter[] { returnFilter });
        String saveName = getSaveName();

        if (saveName == null) {
            // no meta/instanceName field in the form -- see if we have a
            // name for this instance from a previous save attempt...
            if (getContentResolver().getType(getIntent().getData()) == InstanceColumns.CONTENT_ITEM_TYPE) {
                Uri instanceUri = getIntent().getData();
                Cursor instance = null;
                try {
                    instance = getContentResolver().query(instanceUri, null, null, null, null);
                    if (instance.getCount() == 1) {
                        instance.moveToFirst();
                        saveName = instance.getString(instance.getColumnIndex(InstanceColumns.DISPLAY_NAME));
                    }
                } finally {
                    if (instance != null) {
                        instance.close();
                    }
                }
            }
            if (saveName == null) {
                // last resort, default to the form title
                saveName = formController.getFormTitle();
            }
            // present the prompt to allow user to name the form
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.VISIBLE);
            saveAs.setText(saveName);
            saveAs.setEnabled(true);
            saveAs.setVisibility(View.VISIBLE);
        } else {
            // if instanceName is defined in form, this is the name -- no
            // revisions
            // display only the name, not the prompt, and disable edits
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.GONE);
            saveAs.setText(saveName);
            saveAs.setEnabled(false);
            saveAs.setBackgroundColor(Color.WHITE);
            saveAs.setVisibility(View.VISIBLE);
        }

        // override the visibility settings based upon admin preferences
        if (!mAdminPreferences.getBoolean(AdminPreferencesActivity.KEY_SAVE_AS, true)) {
            saveAs.setVisibility(View.GONE);
            TextView sa = (TextView) endView.findViewById(R.id.save_form_as);
            sa.setVisibility(View.GONE);
        }

        // Create 'save' button
        ((Button) endView.findViewById(R.id.save_exit_button)).setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View v) {
                Collect.getInstance().getActivityLogger().logInstanceAction(this, "createView.saveAndExit",
                        instanceComplete.isChecked() ? "saveAsComplete" : "saveIncomplete");
                // Form is marked as 'saved' here.
                if (saveAs.getText().length() < 1) {
                    Toast.makeText(FormEntryActivity.this, R.string.save_as_error, Toast.LENGTH_SHORT).show();
                } else {
                    saveDataToDisk(EXIT, instanceComplete.isChecked(), saveAs.getText().toString());
                }
            }
        });

        if (mBackButton.isShown()) {
            mBackButton.setEnabled(true);
        }
        if (mNextButton.isShown()) {
            mNextButton.setEnabled(false);
        }

        return endView;
    case FormEntryController.EVENT_QUESTION:
    case FormEntryController.EVENT_GROUP:
    case FormEntryController.EVENT_REPEAT:
        ODKView odkv = null;
        // should only be a group here if the event_group is a field-list
        try {
            double depth = (double) formController.getFormIndex().getDepth();
            double local_index = (double) formController.getFormIndex().getLocalIndex();
            double instance_index = (double) formController.getFormIndex().getInstanceIndex();
            Log.i("Question coint", Integer.toString(questioncount));

            Log.i("Depth", Integer.toString(formController.getFormIndex().getDepth()));
            Log.i("Local Index", Integer.toString(formController.getFormIndex().getLocalIndex()));
            Log.i("Instance Index", Integer.toString(formController.getFormIndex().getInstanceIndex()));

            if (swipeCase == NEXT) {

                Log.i("progressValue", Double.toString(progressValue));

            }
            if (swipeCase == PREVIOUS) {
                progressValue = progressValue - (1 - (instance_index * local_index / questioncount * depth));

                Log.i("progressValue", Double.toString(progressValue));
            }
            Log.i("progressValue", Double.toString(progressValue));
            progressUpdate(progressValue, questioncount);
            FormEntryPrompt[] prompts = formController.getQuestionPrompts();
            FormEntryCaption[] groups = formController.getGroupsForCurrentIndex();
            odkv = new ODKView(this, formController.getQuestionPrompts(), groups, advancingPage);
            Log.i(t, "created view for group "
                    + (groups.length > 0 ? groups[groups.length - 1].getLongText() : "[top]") + " "
                    + (prompts.length > 0 ? prompts[0].getQuestionText() : "[no question]"));
        } catch (RuntimeException e) {
            Log.e(t, e.getMessage(), e);
            // this is badness to avoid a crash.
            try {
                event = formController.stepToNextScreenEvent();
                createErrorDialog(e.getMessage(), DO_NOT_EXIT);
            } catch (JavaRosaException e1) {
                Log.e(t, e1.getMessage(), e1);
                createErrorDialog(e.getMessage() + "\n\n" + e1.getCause().getMessage(), DO_NOT_EXIT);
            }
            return createView(event, advancingPage, swipeCase);
        }

        // Makes a "clear answer" menu pop up on long-click
        for (QuestionWidget qw : odkv.getWidgets()) {
            if (!qw.getPrompt().isReadOnly()) {
                registerForContextMenu(qw);
            }
        }

        if (mBackButton.isShown() && mNextButton.isShown()) {
            mBackButton.setEnabled(true);
            mNextButton.setEnabled(true);
        }
        return odkv;
    default:
        Log.e(t, "Attempted to create a view that does not exist.");
        // this is badness to avoid a crash.
        try {
            event = formController.stepToNextScreenEvent();
            createErrorDialog(getString(R.string.survey_internal_error), EXIT);
        } catch (JavaRosaException e) {
            Log.e(t, e.getMessage(), e);
            createErrorDialog(e.getCause().getMessage(), EXIT);
        }
        return createView(event, advancingPage, swipeCase);
    }

}

From source file:com.samknows.measurement.activity.SamKnowsAggregateStatViewerActivity.java

@Override
public void onClick(View v) {
    // Toast.makeText(this,"clicked ..."+v.getId(),3000).show();

    ImageView button = null;
    LinearLayout l = null;// w  w  w  .  ja  v a  2 s .  co m

    int grid = 0;
    int testid = 0;
    boolean buttonfound = false;

    int id = v.getId();
    if (id == R.id.download_header || id == R.id.btn_download_toggle) {
        if (total_download_archive_records > 0) {
            buttonfound = true;
        }
        grid = R.id.agggregate_test1_grid;
        testid = TestResult.DOWNLOAD_TEST_ID;
        l = (LinearLayout) findViewById(R.id.download_content);
        button = (ImageView) findViewById(R.id.btn_download_toggle);

    }

    if (id == R.id.upload_header || id == R.id.btn_upload_toggle) {

        if (total_upload_archive_records > 0) {
            buttonfound = true;
        }
        grid = R.id.agggregate_test2_grid;
        testid = TestResult.UPLOAD_TEST_ID;
        l = (LinearLayout) findViewById(R.id.upload_content);
        button = (ImageView) findViewById(R.id.btn_upload_toggle);
    }

    if (id == R.id.latency_header || id == R.id.btn_latency_toggle) {
        if (total_latency_archive_records > 0) {
            buttonfound = true;
        }
        grid = R.id.agggregate_test3_grid;
        testid = TestResult.LATENCY_TEST_ID;
        l = (LinearLayout) findViewById(R.id.latency_content);
        button = (ImageView) findViewById(R.id.btn_latency_toggle);
    }

    if (id == R.id.packetloss_header || id == R.id.btn_packetloss_toggle) {
        if (total_packetloss_archive_records > 0) {
            buttonfound = true;
        }
        grid = R.id.agggregate_test4_grid;
        testid = TestResult.PACKETLOSS_TEST_ID;
        l = (LinearLayout) findViewById(R.id.packetloss_content);
        button = (ImageView) findViewById(R.id.btn_packetloss_toggle);
    }

    if (id == R.id.jitter_header || id == R.id.btn_jitter_toggle) {
        if (total_jitter_archive_records > 0) {
            buttonfound = true;
        }
        grid = R.id.agggregate_test5_grid;
        testid = TestResult.JITTER_TEST_ID;
        l = (LinearLayout) findViewById(R.id.jitter_content);
        button = (ImageView) findViewById(R.id.btn_jitter_toggle);
    }

    // actions

    if (buttonfound) {

        if (l.getVisibility() == View.INVISIBLE) {

            button.setBackgroundResource(R.drawable.btn_up);
            button.setContentDescription(getString(R.string.close_panel));
            // graphHandler1.update();
            l.measure(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);
            target_height = l.getMeasuredHeight();

            clearGrid(grid);
            loadDownloadGrid(testid, grid, 0, 5);

            l.getLayoutParams().height = 0;
            l.setVisibility(View.VISIBLE);

            ResizeAnimation animation = null;

            animation = new ResizeAnimation(l, target_height, 0, false);
            animation.setDuration(500);
            animation.setFillEnabled(true);
            animation.setFillAfter(true);

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

                @Override
                public void onAnimationRepeat(Animation animation) {
                }

                @Override
                public void onAnimationEnd(Animation animation) {
                }
            });
            l.startAnimation(animation);

        } else {

            ResizeAnimation animation = null;
            int required_height = l.getMeasuredHeight();
            animation = new ResizeAnimation(l, 0, target_height, false);
            animation.setDuration(500);
            animation.setFillEnabled(true);
            animation.setFillAfter(true);
            MyAnimationListener animationListener = new MyAnimationListener();
            animationListener.setView(l);
            animation.setAnimationListener(animationListener);
            l.startAnimation(animation);

            button.setBackgroundResource(R.drawable.btn_down);
            button.setContentDescription(getString(R.string.open_panel));
        }
    }

}