Example usage for android.widget ImageView setImageDrawable

List of usage examples for android.widget ImageView setImageDrawable

Introduction

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

Prototype

public void setImageDrawable(@Nullable Drawable drawable) 

Source Link

Document

Sets a drawable as the content of this ImageView.

Usage

From source file:com.amaze.filemanager.activities.MainActivity.java

public void bbar(final Main main) {
    final String text = main.CURRENT_PATH;
    try {//from  ww  w. j av  a 2s . co m
        buttons.removeAllViews();
        buttons.setMinimumHeight(pathbar.getHeight());
        Drawable arrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_holo_dark);
        Bundle b = utils.getPaths(text, this);
        ArrayList<String> names = b.getStringArrayList("names");
        ArrayList<String> rnames = new ArrayList<String>();

        for (int i = names.size() - 1; i >= 0; i--) {
            rnames.add(names.get(i));
        }

        ArrayList<String> paths = b.getStringArrayList("paths");
        final ArrayList<String> rpaths = new ArrayList<String>();

        for (int i = paths.size() - 1; i >= 0; i--) {
            rpaths.add(paths.get(i));
        }
        View view = new View(this);
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(toolbar.getContentInsetLeft(),
                LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(params1);
        buttons.addView(view);
        for (int i = 0; i < names.size(); i++) {
            final int k = i;
            ImageView v = new ImageView(this);
            v.setImageDrawable(arrow);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER_VERTICAL;
            v.setLayoutParams(params);
            final int index = i;
            if (rpaths.get(i).equals("/")) {
                ImageButton ib = new ImageButton(this);
                ib.setImageDrawable(icons.getRootDrawable());
                ib.setBackgroundColor(Color.parseColor("#00ffffff"));
                ib.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View p1) {
                        main.loadlist(("/"), false, main.openMode);
                        timer.cancel();
                        timer.start();
                    }
                });
                ib.setLayoutParams(params);
                buttons.addView(ib);
                if (names.size() - i != 1)
                    buttons.addView(v);
            } else if (isStorage(rpaths.get(i))) {
                ImageButton ib = new ImageButton(this);
                ib.setImageDrawable(icons.getSdDrawable());
                ib.setBackgroundColor(Color.parseColor("#00ffffff"));
                ib.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View p1) {
                        main.loadlist((rpaths.get(k)), false, main.openMode);
                        timer.cancel();
                        timer.start();
                    }
                });
                ib.setLayoutParams(params);
                buttons.addView(ib);
                if (names.size() - i != 1)
                    buttons.addView(v);
            } else {
                Button button = new Button(this);
                button.setText(rnames.get(index));
                button.setTextColor(getResources().getColor(android.R.color.white));
                button.setTextSize(13);
                button.setLayoutParams(params);
                button.setBackgroundResource(0);
                button.setOnClickListener(new Button.OnClickListener() {

                    public void onClick(View p1) {
                        main.loadlist((rpaths.get(k)), false, main.openMode);
                        main.loadlist((rpaths.get(k)), false, main.openMode);
                        timer.cancel();
                        timer.start();
                    }
                });
                button.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {

                        File file1 = new File(rpaths.get(index));
                        copyToClipboard(MainActivity.this, file1.getPath());
                        Toast.makeText(MainActivity.this, getResources().getString(R.string.pathcopied),
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });

                buttons.addView(button);
                if (names.size() - i != 1)
                    buttons.addView(v);
            }
        }

        scroll.post(new Runnable() {
            @Override
            public void run() {
                sendScroll(scroll);
                sendScroll(scroll1);
            }
        });

        if (buttons.getVisibility() == View.VISIBLE) {
            timer.cancel();
            timer.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
        System.out.println("button view not available");
    }
}

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

@Override
public void bindCollectionItemView(Context context, View view, int groupId, int indexInGroup, int dataIndex,
        Object tag) {/*  w ww  . j  a va  2  s.  co m*/
    if (mCursor == null || !mCursor.moveToPosition(dataIndex)) {
        LOGW(TAG, "Can't bind collection view item, dataIndex=" + dataIndex
                + (mCursor == null ? ": cursor is null" : ": bad data index."));
        return;
    }

    final String sessionId = mCursor.getString(SessionsQuery.SESSION_ID);
    if (sessionId == null) {
        return;
    }

    // first, read session info from cursor and put it in convenience variables
    final String sessionTitle = mCursor.getString(SessionsQuery.TITLE);
    final String speakerNames = mCursor.getString(SessionsQuery.SPEAKER_NAMES);
    final String sessionAbstract = mCursor.getString(SessionsQuery.ABSTRACT);
    final long sessionStart = mCursor.getLong(SessionsQuery.SESSION_START);
    final long sessionEnd = mCursor.getLong(SessionsQuery.SESSION_END);
    final String roomName = mCursor.getString(SessionsQuery.ROOM_NAME);
    int sessionColor = mCursor.getInt(SessionsQuery.COLOR);
    sessionColor = sessionColor == 0 ? getResources().getColor(R.color.default_session_color) : sessionColor;
    int darkSessionColor = 0;
    final String snippet = mIsSearchCursor ? mCursor.getString(SessionsQuery.SNIPPET) : null;
    final Spannable styledSnippet = mIsSearchCursor ? buildStyledSnippet(snippet) : null;
    final boolean starred = mCursor.getInt(SessionsQuery.IN_MY_SCHEDULE) != 0;
    final String[] tags = mCursor.getString(SessionsQuery.TAGS).split(",");

    // now let's compute a few pieces of information from the data, which we will use
    // later to decide what to render where
    final boolean hasLivestream = !TextUtils.isEmpty(mCursor.getString(SessionsQuery.LIVESTREAM_URL));
    final long now = UIUtils.getCurrentTime(context);
    final boolean happeningNow = now >= sessionStart && now <= sessionEnd;

    // text that says "LIVE" if session is live, or empty if session is not live
    final String liveNowText = hasLivestream ? " " + UIUtils.getLiveBadgeText(context, sessionStart, sessionEnd)
            : "";

    // get reference to all the views in the layout we will need
    final TextView titleView = (TextView) view.findViewById(R.id.session_title);
    final TextView subtitleView = (TextView) view.findViewById(R.id.session_subtitle);
    final TextView shortSubtitleView = (TextView) view.findViewById(R.id.session_subtitle_short);
    final TextView snippetView = (TextView) view.findViewById(R.id.session_snippet);
    final TextView abstractView = (TextView) view.findViewById(R.id.session_abstract);
    final TextView categoryView = (TextView) view.findViewById(R.id.session_category);
    final View sessionTargetView = view.findViewById(R.id.session_target);

    if (sessionColor == 0) {
        // use default
        sessionColor = mDefaultSessionColor;
    }

    if (mNoTrackBranding) {
        sessionColor = getResources().getColor(R.color.no_track_branding_session_color);
    }

    darkSessionColor = UIUtils.scaleSessionColorToDefaultBG(sessionColor);

    ImageView photoView = (ImageView) view.findViewById(R.id.session_photo_colored);
    if (photoView != null) {
        if (!mPreloader.isDimensSet()) {
            final ImageView finalPhotoView = photoView;
            photoView.post(new Runnable() {
                @Override
                public void run() {
                    mPreloader.setDimens(finalPhotoView.getWidth(), finalPhotoView.getHeight());
                }
            });
        }
        // colored
        photoView
                .setColorFilter(mNoTrackBranding
                        ? new PorterDuffColorFilter(
                                getResources().getColor(R.color.no_track_branding_session_tile_overlay),
                                PorterDuff.Mode.SRC_ATOP)
                        : UIUtils.makeSessionImageScrimColorFilter(darkSessionColor));
    } else {
        photoView = (ImageView) view.findViewById(R.id.session_photo);
    }
    ViewCompat.setTransitionName(photoView, "photo_" + sessionId);

    // when we load a photo, it will fade in from transparent so the
    // background of the container must be the session color to avoid a white flash
    ViewParent parent = photoView.getParent();
    if (parent != null && parent instanceof View) {
        ((View) parent).setBackgroundColor(darkSessionColor);
    } else {
        photoView.setBackgroundColor(darkSessionColor);
    }

    String photo = mCursor.getString(SessionsQuery.PHOTO_URL);
    if (!TextUtils.isEmpty(photo)) {
        mImageLoader.loadImage(photo, photoView, true /*crop*/);
    } else {
        // cleaning the (potentially) recycled photoView, in case this session has no photo:
        photoView.setImageDrawable(null);
    }

    // render title
    titleView.setText(sessionTitle == null ? "?" : sessionTitle);

    // render subtitle into either the subtitle view, or the short subtitle view, as available
    if (subtitleView != null) {
        subtitleView.setText(UIUtils.formatSessionSubtitle(sessionStart, sessionEnd, roomName, mBuffer, context)
                + liveNowText);
    } else if (shortSubtitleView != null) {
        shortSubtitleView.setText(
                UIUtils.formatSessionSubtitle(sessionStart, sessionEnd, roomName, mBuffer, context, true)
                        + liveNowText);
    }

    // render category
    if (categoryView != null) {
        TagMetadata.Tag groupTag = mTagMetadata.getSessionGroupTag(tags);
        if (groupTag != null && !Config.Tags.SESSIONS.equals(groupTag.getId())) {
            categoryView.setText(groupTag.getName());
            categoryView.setVisibility(View.VISIBLE);
        } else {
            categoryView.setVisibility(View.GONE);
        }
    }

    // if a snippet view is available, render the session snippet there.
    if (snippetView != null) {
        if (mIsSearchCursor) {
            // render the search snippet into the snippet view
            snippetView.setText(styledSnippet);
        } else {
            // render speaker names and abstracts into the snippet view
            mBuffer.setLength(0);
            if (!TextUtils.isEmpty(speakerNames)) {
                mBuffer.append(speakerNames).append(". ");
            }
            if (!TextUtils.isEmpty(sessionAbstract)) {
                mBuffer.append(sessionAbstract);
            }
            snippetView.setText(mBuffer.toString());
        }
    }

    if (abstractView != null && !mIsSearchCursor) {
        // render speaker names and abstracts into the abstract view
        mBuffer.setLength(0);
        if (!TextUtils.isEmpty(speakerNames)) {
            mBuffer.append(speakerNames).append("\n\n");
        }
        if (!TextUtils.isEmpty(sessionAbstract)) {
            mBuffer.append(sessionAbstract);
        }
        abstractView.setText(mBuffer.toString());
    }

    // show or hide the "in my schedule" indicator
    view.findViewById(R.id.indicator_in_schedule).setVisibility(starred ? View.VISIBLE : View.INVISIBLE);

    // if we are in condensed mode and this card is the hero card (big card at the top
    // of the screen), set up the message card if necessary.
    if (!useExpandedMode() && groupId == HERO_GROUP_ID) {
        // this is the hero view, so we might want to show a message card
        final boolean cardShown = setupMessageCard(view);

        // if this is the wide hero layout, show or hide the card or the session abstract
        // view, as appropriate (they are mutually exclusive).
        final View cardContainer = view.findViewById(R.id.message_card_container_wide);
        final View abstractContainer = view.findViewById(R.id.session_abstract);
        if (cardContainer != null && abstractContainer != null) {
            cardContainer.setVisibility(cardShown ? View.VISIBLE : View.GONE);
            abstractContainer.setVisibility(cardShown ? View.GONE : View.VISIBLE);
            abstractContainer.setBackgroundColor(darkSessionColor);
        }
    }

    // if this session is live right now, display the "LIVE NOW" icon on top of it
    View liveNowBadge = view.findViewById(R.id.live_now_badge);
    if (liveNowBadge != null) {
        liveNowBadge.setVisibility(happeningNow && hasLivestream ? View.VISIBLE : View.GONE);
    }

    // if this view is clicked, open the session details view
    final View finalPhotoView = photoView;
    sessionTargetView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            mCallbacks.onSessionSelected(sessionId, finalPhotoView);
        }
    });

    // animate this card
    if (dataIndex > mMaxDataIndexAnimated) {
        mMaxDataIndexAnimated = dataIndex;
    }
}

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

/**
 * Creates a view given the View type and an event
 *
 * @param event/*  w  ww .  ja  v  a 2  s.  c o 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.amaze.carbonfilemanager.activities.MainActivity.java

void setDrawerHeaderBackground() {
    new Thread(new Runnable() {
        public void run() {
            if (sharedPref.getBoolean("plus_pic", false))
                return;
            String path = sharedPref.getString("drawer_header_path", null);
            if (path == null)
                return;
            try {
                final ImageView headerImageView = new ImageView(MainActivity.this);
                headerImageView.setImageDrawable(drawerHeaderParent.getBackground());
                mImageLoader.get(path, new ImageLoader.ImageListener() {
                    @Override//from w  ww .java2  s .  com
                    public void onResponse(ImageLoader.ImageContainer response, boolean isImmediate) {
                        headerImageView.setImageBitmap(response.getBitmap());
                        drawerHeaderView.setBackgroundResource(R.drawable.amaze_header_2);
                    }

                    @Override
                    public void onErrorResponse(VolleyError error) {
                    }
                });
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
    }).run();
}

From source file:com.amaze.carbonfilemanager.activities.MainActivity.java

public void bbar(final MainFragment mainFrag) {
    final String path = mainFrag.CURRENT_PATH;
    try {//w w w.  jav  a  2  s  .com
        buttons.removeAllViews();
        buttons.setMinimumHeight(pathbar.getHeight());
        Drawable arrow = getResources().getDrawable(R.drawable.abc_ic_ab_back_holo_dark);
        Bundle bundle = utils.getPaths(path, this);
        ArrayList<String> names = bundle.getStringArrayList("names");
        ArrayList<String> rnames = bundle.getStringArrayList("names");
        Collections.reverse(rnames);

        ArrayList<String> paths = bundle.getStringArrayList("paths");
        final ArrayList<String> rpaths = bundle.getStringArrayList("paths");
        Collections.reverse(rpaths);

        View view = new View(this);
        LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(toolbar.getContentInsetLeft(),
                LinearLayout.LayoutParams.WRAP_CONTENT);
        view.setLayoutParams(params1);
        buttons.addView(view);
        for (int i = 0; i < names.size(); i++) {
            final int k = i;
            ImageView v = new ImageView(this);
            v.setImageDrawable(arrow);
            LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
                    LinearLayout.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT);
            params.gravity = Gravity.CENTER_VERTICAL;
            v.setLayoutParams(params);
            final int index = i;
            if (rpaths.get(i).equals("/")) {
                ImageButton ib = new ImageButton(this);
                ib.setImageDrawable(icons.getRootDrawable());
                ib.setBackgroundColor(Color.TRANSPARENT);
                ib.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View p1) {
                        mainFrag.loadlist(("/"), false, mainFrag.openMode);
                        timer.cancel();
                        timer.start();
                    }
                });
                ib.setLayoutParams(params);
                buttons.addView(ib);
                if (names.size() - i != 1)
                    buttons.addView(v);
            } else if (isStorage(rpaths.get(i))) {
                ImageButton ib = new ImageButton(this);
                ib.setImageDrawable(icons.getSdDrawable());
                ib.setBackgroundColor(Color.TRANSPARENT);
                ib.setOnClickListener(new View.OnClickListener() {

                    public void onClick(View p1) {
                        mainFrag.loadlist((rpaths.get(k)), false, mainFrag.openMode);
                        timer.cancel();
                        timer.start();
                    }
                });
                ib.setLayoutParams(params);
                buttons.addView(ib);
                if (names.size() - i != 1)
                    buttons.addView(v);
            } else {
                Button b = new Button(this);
                b.setText(rnames.get(index));
                b.setTextColor(Utils.getColor(this, android.R.color.white));
                b.setTextSize(13);
                b.setLayoutParams(params);
                b.setBackgroundResource(0);
                b.setOnClickListener(new Button.OnClickListener() {

                    public void onClick(View p1) {
                        mainFrag.loadlist((rpaths.get(k)), false, mainFrag.openMode);
                        mainFrag.loadlist((rpaths.get(k)), false, mainFrag.openMode);
                        timer.cancel();
                        timer.start();
                    }
                });
                b.setOnLongClickListener(new View.OnLongClickListener() {
                    @Override
                    public boolean onLongClick(View view) {

                        File file1 = new File(rpaths.get(index));
                        copyToClipboard(MainActivity.this, file1.getPath());
                        Toast.makeText(MainActivity.this, getResources().getString(R.string.pathcopied),
                                Toast.LENGTH_SHORT).show();
                        return false;
                    }
                });

                buttons.addView(b);
                if (names.size() - i != 1)
                    buttons.addView(v);
            }
        }

        scroll.post(new Runnable() {
            @Override
            public void run() {
                sendScroll(scroll);
                sendScroll(scroll1);
            }
        });

        if (buttons.getVisibility() == View.VISIBLE) {
            timer.cancel();
            timer.start();
        }
    } catch (Exception e) {
        e.printStackTrace();
        Log.d("BBar", "button view not available");
    }
}

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

public static void showEditMode(final Activity activity, final ShortcutInfo shortcutInfo) {
    ContextThemeWrapper theme;// w w w  .  ja  v  a 2 s  . c o  m
    final Set<String> setString = new HashSet<String>();
    if (Build.VERSION.SDK_INT == Build.VERSION_CODES.M) {
        theme = new ContextThemeWrapper(activity, R.style.AlertDialogCustomAPI23);
    } else {
        theme = new ContextThemeWrapper(activity, R.style.AlertDialogCustom);
    }

    AlertDialog.Builder alert = new AlertDialog.Builder(theme);
    LinearLayout layout = new LinearLayout(activity.getApplicationContext());
    layout.setOrientation(LinearLayout.VERTICAL);
    layout.setPadding(100, 0, 100, 100);

    final ImageView img = new ImageView(activity.getApplicationContext());
    Drawable icon = null;
    if (Utilities.getAppIconPackageNamePrefEnabled(activity.getApplicationContext()) != null) {
        if (Utilities.getAppIconPackageNamePrefEnabled(activity.getApplicationContext()).equals("NULL")) {
            if (Utilities.loadBitmapPref(Launcher.getLauncherActivity(),
                    shortcutInfo.getTargetComponent().getPackageName()) != null) {
                icon = new BitmapDrawable(activity.getResources(),
                        Utilities.loadBitmapPref(activity, shortcutInfo.getTargetComponent().getPackageName()));
            } else {
                icon = new BitmapDrawable(activity.getResources(),
                        shortcutInfo.getIcon(new IconCache(activity.getApplicationContext(),
                                Launcher.getLauncher(activity).getDeviceProfile().inv)));
            }
        } else {

            if (Utilities.loadBitmapPref(Launcher.getLauncherActivity(),
                    shortcutInfo.getTargetComponent().getPackageName()) != null) {
                icon = new BitmapDrawable(activity.getResources(),
                        Utilities.loadBitmapPref(activity, shortcutInfo.getTargetComponent().getPackageName()));
            } else {
                icon = new BitmapDrawable(activity.getResources(),
                        Launcher.getIcons().get(shortcutInfo.getTargetComponent().getPackageName()));
            }
        }
    } else {

        if (Utilities.loadBitmapPref(Launcher.getLauncherActivity(),
                shortcutInfo.getTargetComponent().getPackageName()) != null) {
            icon = new BitmapDrawable(activity.getResources(),
                    Utilities.loadBitmapPref(activity, shortcutInfo.getTargetComponent().getPackageName()));
        } else {
            icon = new BitmapDrawable(activity.getResources(),
                    shortcutInfo.getIcon(new IconCache(activity.getApplicationContext(),
                            Launcher.getLauncher(Launcher.getLauncherActivity()).getDeviceProfile().inv)));
        }
    }
    img.setImageDrawable(icon);
    img.setPadding(0, 100, 0, 0);

    img.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            showIconPack(activity, shortcutInfo);
        }
    });

    final EditText titleBox = new EditText(activity.getApplicationContext());

    try {
        Set<String> title = new HashSet<>(
                Utilities.getTitle(activity, shortcutInfo.getTargetComponent().getPackageName()));
        for (Iterator<String> it = title.iterator(); it.hasNext();) {
            String titleApp = it.next();
            titleBox.setText(titleApp);
        }
    } catch (Exception e) {
        titleBox.setText(shortcutInfo.title);
    }

    titleBox.getBackground().mutate().setColorFilter(
            ContextCompat.getColor(activity.getApplicationContext(), R.color.colorPrimary),
            PorterDuff.Mode.SRC_ATOP);

    layout.addView(img);
    layout.addView(titleBox);

    alert.setTitle(activity.getApplicationContext().getResources().getString(R.string.edit_label));
    alert.setView(layout);

    alert.setPositiveButton(activity.getApplicationContext().getString(R.string.ok),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    for (ItemInfo itemInfo : AllAppsList.data) {
                        if (shortcutInfo.getTargetComponent().getPackageName()
                                .equals(itemInfo.getTargetComponent().getPackageName())) {
                            setString.add(titleBox.getText().toString());
                            getPrefs(activity.getApplicationContext()).edit()
                                    .putStringSet(itemInfo.getTargetComponent().getPackageName(), setString)
                                    .apply();
                            Launcher.getShortcutsCreation().clearAllLayout();
                            applyChange(activity);
                        }
                    }
                }
            });

    alert.setNegativeButton(activity.getApplicationContext().getString(R.string.cancel),
            new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int whichButton) {
                    Launcher.getShortcutsCreation().clearAllLayout();
                }
            });
    alert.show();
}

From source file:com.android.contacts.common.ContactPhotoManager.java

/**
 * Checks if the photo is present in cache.  If so, sets the photo on the view.
 *
 * @return false if the photo needs to be (re)loaded from the provider.
 *///from   w w w  . j  a  v a  2s  .  co m
private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) {
    BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
    if (holder == null) {
        // The bitmap has not been loaded ==> show default avatar
        request.applyDefaultImage(view, request.mIsCircular);
        return false;
    }

    if (holder.bytes == null) {
        request.applyDefaultImage(view, request.mIsCircular);
        return holder.fresh;
    }

    Bitmap cachedBitmap = holder.bitmapRef == null ? null : holder.bitmapRef.get();
    if (cachedBitmap == null) {
        if (holder.bytes.length < 8 * 1024) {
            // Small thumbnails are usually quick to inflate. Let's do that on the UI thread
            inflateBitmap(holder, request.getRequestedExtent());
            cachedBitmap = holder.bitmap;
            if (cachedBitmap == null)
                return false;
        } else {
            // This is bigger data. Let's send that back to the Loader so that we can
            // inflate this in the background
            request.applyDefaultImage(view, request.mIsCircular);
            return false;
        }
    }

    final Drawable previousDrawable = view.getDrawable();
    if (fadeIn && previousDrawable != null) {
        final Drawable[] layers = new Drawable[2];
        // Prevent cascade of TransitionDrawables.
        if (previousDrawable instanceof TransitionDrawable) {
            final TransitionDrawable previousTransitionDrawable = (TransitionDrawable) previousDrawable;
            layers[0] = previousTransitionDrawable
                    .getDrawable(previousTransitionDrawable.getNumberOfLayers() - 1);
        } else {
            layers[0] = previousDrawable;
        }
        layers[1] = getDrawableForBitmap(mContext.getResources(), cachedBitmap, request);
        TransitionDrawable drawable = new TransitionDrawable(layers);
        view.setImageDrawable(drawable);
        drawable.startTransition(FADE_TRANSITION_DURATION);
    } else {
        view.setImageDrawable(getDrawableForBitmap(mContext.getResources(), cachedBitmap, request));
    }

    // Put the bitmap in the LRU cache. But only do this for images that are small enough
    // (we require that at least six of those can be cached at the same time)
    if (cachedBitmap.getByteCount() < mBitmapCache.maxSize() / 6) {
        mBitmapCache.put(request.getKey(), cachedBitmap);
    }

    // Soften the reference
    holder.bitmap = null;

    return holder.fresh;
}

From source file:com.android.tv.settings.dialog.old.BaseDialogFragment.java

public void performEntryTransition(final Activity activity, final ViewGroup contentView, int iconResourceId,
        Uri iconResourceUri, final ImageView icon, final TextView title, final TextView description,
        final TextView breadcrumb) {
    // Pull out the root layout of the dialog and set the background drawable, to be
    // faded in during the transition.
    final ViewGroup twoPane = (ViewGroup) contentView.getChildAt(0);
    twoPane.setVisibility(View.INVISIBLE);

    // If the appropriate data is embedded in the intent and there is an icon specified
    // in the content fragment, we animate the icon from its initial position to the final
    // position. Otherwise, we perform a simpler transition in which the ActionFragment
    // slides in and the ContentFragment text fields slide in.
    mIntroAnimationInProgress = true;/* w w w .  java  2s  .com*/
    List<TransitionImage> images = TransitionImage.readMultipleFromIntent(activity, activity.getIntent());
    TransitionImageAnimation ltransitionAnimation = null;
    final Uri iconUri;
    final int color;
    if (images != null && images.size() > 0) {
        if (iconResourceId != 0) {
            iconUri = Uri.parse(UriUtils.getAndroidResourceUri(activity, iconResourceId));
        } else if (iconResourceUri != null) {
            iconUri = iconResourceUri;
        } else {
            iconUri = null;
        }
        TransitionImage src = images.get(0);
        color = src.getBackground();
        if (iconUri != null) {
            ltransitionAnimation = new TransitionImageAnimation(contentView);
            ltransitionAnimation.addTransitionSource(src);
            ltransitionAnimation.transitionDurationMs(ANIMATE_IN_DURATION).transitionStartDelayMs(0)
                    .interpolator(new DecelerateInterpolator(1f));
        }
    } else {
        iconUri = null;
        color = 0;
    }
    final TransitionImageAnimation transitionAnimation = ltransitionAnimation;

    // Fade out the old activity, and hard cut the new activity.
    activity.overridePendingTransition(R.anim.hard_cut_in, R.anim.fade_out);

    int bgColor = mFragment.getResources().getColor(R.color.dialog_activity_background);
    mBgDrawable.setColor(bgColor);
    mBgDrawable.setAlpha(0);
    twoPane.setBackground(mBgDrawable);

    // If we're animating the icon, we create a new ImageView in which to place the embedded
    // bitmap. We place it in the root layout to match its location in the previous activity.
    mShadowLayer = (FrameLayoutWithShadows) twoPane.findViewById(R.id.shadow_layout);
    if (transitionAnimation != null) {
        transitionAnimation.listener(new TransitionImageAnimation.Listener() {
            @Override
            public void onRemovedView(TransitionImage src, TransitionImage dst) {
                if (icon != null) {
                    //want to make sure that users still see at least the source image
                    // if the dst image is too large to finish downloading before the
                    // animation is done. Check if the icon is not visible. This mean
                    // BaseContentFragement have not finish downloading the image yet.
                    if (icon.getVisibility() != View.VISIBLE) {
                        icon.setImageDrawable(src.getBitmap());
                        int intrinsicWidth = icon.getDrawable().getIntrinsicWidth();
                        LayoutParams lp = icon.getLayoutParams();
                        lp.height = lp.width * icon.getDrawable().getIntrinsicHeight() / intrinsicWidth;
                        icon.setVisibility(View.VISIBLE);
                    }
                    icon.setAlpha(1f);
                }
                if (mShadowLayer != null) {
                    mShadowLayer.setShadowsAlpha(1f);
                }
                onIntroAnimationFinished();
            }
        });
        icon.setAlpha(0f);
        if (mShadowLayer != null) {
            mShadowLayer.setShadowsAlpha(0f);
        }
    }

    // We need to defer the remainder of the animation preparation until the first
    // layout has occurred, as we don't yet know the final location of the icon.
    twoPane.getViewTreeObserver().addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() {
        @Override
        public void onGlobalLayout() {
            twoPane.getViewTreeObserver().removeOnGlobalLayoutListener(this);
            // if we buildLayer() at this time,  the texture is actually not created
            // delay a little so we can make sure all hardware layer is created before
            // animation, in that way we can avoid the jittering of start animation
            twoPane.postOnAnimationDelayed(mEntryAnimationRunnable, ANIMATE_DELAY);
        }

        final Runnable mEntryAnimationRunnable = new Runnable() {
            @Override
            public void run() {
                if (!mFragment.isAdded()) {
                    // We have been detached before this could run, so just bail
                    return;
                }

                twoPane.setVisibility(View.VISIBLE);
                final int secondaryDelay = SLIDE_IN_DISTANCE;

                // Fade in the activity background protection
                ObjectAnimator oa = ObjectAnimator.ofInt(mBgDrawable, "alpha", 255);
                oa.setDuration(ANIMATE_IN_DURATION);
                oa.setStartDelay(secondaryDelay);
                oa.setInterpolator(new DecelerateInterpolator(1.0f));
                oa.start();

                View actionFragmentView = activity.findViewById(mActionAreaId);
                boolean isRtl = ViewCompat.getLayoutDirection(contentView) == ViewCompat.LAYOUT_DIRECTION_RTL;
                int startDist = isRtl ? SLIDE_IN_DISTANCE : -SLIDE_IN_DISTANCE;
                int endDist = isRtl ? -actionFragmentView.getMeasuredWidth()
                        : actionFragmentView.getMeasuredWidth();

                // Fade in and slide in the ContentFragment TextViews from the start.
                prepareAndAnimateView(title, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);
                prepareAndAnimateView(breadcrumb, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);
                prepareAndAnimateView(description, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);

                // Fade in and slide in the ActionFragment from the end.
                prepareAndAnimateView(actionFragmentView, 0, endDist, secondaryDelay, ANIMATE_IN_DURATION,
                        new DecelerateInterpolator(1.0f), false);

                if (icon != null && transitionAnimation != null) {
                    // now we get the icon view in place,  update the transition target
                    TransitionImage target = new TransitionImage();
                    target.setUri(iconUri);
                    target.createFromImageView(icon);
                    if (icon.getBackground() instanceof ColorDrawable) {
                        ColorDrawable d = (ColorDrawable) icon.getBackground();
                        target.setBackground(d.getColor());
                    }
                    transitionAnimation.addTransitionTarget(target);
                    transitionAnimation.startTransition();
                } else if (icon != null) {
                    prepareAndAnimateView(icon, 0, startDist, secondaryDelay, ANIMATE_IN_DURATION,
                            new DecelerateInterpolator(1.0f), true /* is the icon */);
                    if (mShadowLayer != null) {
                        mShadowLayer.setShadowsAlpha(0f);
                    }
                }
            }
        };
    });
}

From source file:com.android.contacts.ContactPhotoManager.java

/**
 * Checks if the photo is present in cache.  If so, sets the photo on the view.
 *
 * @return false if the photo needs to be (re)loaded from the provider.
 *///from w  w  w. j  a  v  a  2 s. c  o  m
private boolean loadCachedPhoto(ImageView view, Request request, boolean fadeIn) {
    BitmapHolder holder = mBitmapHolderCache.get(request.getKey());
    if (holder == null) {
        // The bitmap has not been loaded ==> show default avatar
        request.applyDefaultImage(view, request.mIsCircular);
        return false;
    }

    if (holder.bytes == null || holder.bytes.length == 0) {
        request.applyDefaultImage(view, request.mIsCircular);
        return holder.fresh;
    }

    Bitmap cachedBitmap = holder.bitmapRef == null ? null : holder.bitmapRef.get();
    if (cachedBitmap == null) {
        if (holder.bytes.length < 8 * 1024) {
            // Small thumbnails are usually quick to inflate. Let's do that on the UI thread
            inflateBitmap(holder, request.getRequestedExtent());
            cachedBitmap = holder.bitmap;
            if (cachedBitmap == null)
                return false;
        } else {
            // This is bigger data. Let's send that back to the Loader so that we can
            // inflate this in the background
            request.applyDefaultImage(view, request.mIsCircular);
            return false;
        }
    }

    final Drawable previousDrawable = view.getDrawable();
    if (fadeIn && previousDrawable != null) {
        final Drawable[] layers = new Drawable[2];
        // Prevent cascade of TransitionDrawables.
        if (previousDrawable instanceof TransitionDrawable) {
            final TransitionDrawable previousTransitionDrawable = (TransitionDrawable) previousDrawable;
            layers[0] = previousTransitionDrawable
                    .getDrawable(previousTransitionDrawable.getNumberOfLayers() - 1);
        } else {
            layers[0] = previousDrawable;
        }
        layers[1] = getDrawableForBitmap(mContext.getResources(), cachedBitmap, request);
        TransitionDrawable drawable = new TransitionDrawable(layers);
        view.setImageDrawable(drawable);
        drawable.startTransition(FADE_TRANSITION_DURATION);
    } else {
        view.setImageDrawable(getDrawableForBitmap(mContext.getResources(), cachedBitmap, request));
    }

    // Put the bitmap in the LRU cache. But only do this for images that are small enough
    // (we require that at least six of those can be cached at the same time)
    if (cachedBitmap.getByteCount() < mBitmapCache.maxSize() / 6) {
        mBitmapCache.put(request.getKey(), cachedBitmap);
    }

    // Soften the reference
    holder.bitmap = null;

    return holder.fresh;
}