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:no.ntnu.idi.socialhitchhiking.map.MapActivityAddPickupAndDropoff.java

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

    // Getting the selected journey
    Journey journey = getApp().getSelectedJourney();

    // Setting up tabs
    TabHost tabs = (TabHost) findViewById(R.id.tabhost);
    tabs.setup();// w w w  . j av  a2 s .  c  o m

    // Adding Ride tab
    TabHost.TabSpec specRide = tabs.newTabSpec("tag1");
    specRide.setContent(R.id.ride_tab);
    specRide.setIndicator("Ride");
    tabs.addTab(specRide);

    // Adding Driver tab
    TabHost.TabSpec specDriver = tabs.newTabSpec("tag2");
    specDriver.setContent(R.id.driver_tab);
    specDriver.setIndicator("Driver");
    tabs.addTab(specDriver);

    // Adding the pickup location address text
    ((AutoCompleteTextView) findViewById(R.id.pickupText))
            .setText(getIntent().getExtras().getString("pickupString"));

    // Adding the dropoff location address text
    ((AutoCompleteTextView) findViewById(R.id.dropoffText))
            .setText(getIntent().getExtras().getString("dropoffString"));

    // Drawing the pickup and dropoff locations on the map
    setPickupLocation();
    setDropOffLocation();

    // Adding image of the driver
    User driver = journey.getRoute().getOwner();
    picture = (ImageView) findViewById(R.id.mapViewPickupImage);

    // Create an object for subclass of AsyncTask
    GetImage task = new GetImage(picture, this);
    // Execute the task: Get image from url and add it to the ImageView
    task.execute(driver.getPictureURL());

    // Adding the name of the driver
    ((TextView) findViewById(R.id.mapViewPickupTextViewName)).setText(driver.getFullName());

    // Getting the drivers preferences for this ride
    TripPreferences pref = journey.getTripPreferences();

    // Setting the smoking preference
    if (pref.getSmoking()) {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewSmokingIcon))
                .setImageResource(R.drawable.green_check);
    } else {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewSmokingIcon))
                .setImageResource(R.drawable.red_cross);
    }
    // Setting the animals preference
    if (pref.getAnimals()) {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewAnimalsIcon))
                .setImageResource(R.drawable.green_check);
    } else {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewAnimalsIcon))
                .setImageResource(R.drawable.red_cross);
    }
    // Setting the breaks preference
    if (pref.getBreaks()) {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewBreaksIcon))
                .setImageResource(R.drawable.green_check);
    } else {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewBreaksIcon))
                .setImageResource(R.drawable.red_cross);
    }
    // Setting the music preference
    if (pref.getMusic()) {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewMusicIcon))
                .setImageResource(R.drawable.green_check);
    } else {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewMusicIcon)).setImageResource(R.drawable.red_cross);
    }
    // Setting the talking preference
    if (pref.getTalking()) {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewTalkingIcon))
                .setImageResource(R.drawable.green_check);
    } else {
        ((ImageView) findViewById(R.id.mapViewPickupImageViewTalkingIcon))
                .setImageResource(R.drawable.red_cross);
    }

    // Setting the number of available seats
    ((TextView) findViewById(R.id.mapViewPickupTextViewSeats))
            .setText(pref.getSeatsAvailable() + " available seats");

    // Setting the age of the driver
    ((TextView) findViewById(R.id.mapViewPickupTextViewAge)).setText("Age: " + driver.getAge());

    // Adding the gender of the driver
    if (driver.getGender() != null) {
        if (driver.getGender().equals("m")) {
            ((ImageView) findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.male);
        } else if (driver.getGender().equals("f")) {
            ((ImageView) findViewById(R.id.mapViewPickupImageViewGender)).setImageResource(R.drawable.female);
        }
    }

    // Addring the rating of the driver
    ((TextView) findViewById(R.id.recommendations)).setText("Recommendations: " + (int) driver.getRating());

    // Setting the drivers mobile number
    ((TextView) findViewById(R.id.mapViewPickupTextViewPhone)).setText("Mobile: " + driver.getPhone());

    try {
        // Getting the car image
        Car dummyCar = new Car(driver.getCarId(), "Dummy", 0.0); //"Dummy" and 0.0 are dummy vars. getApp() etc sends the current user's carid
        Request carReq = new CarRequest(RequestType.GET_CAR, getApp().getUser(), dummyCar);
        CarResponse carRes = (CarResponse) RequestTask.sendRequest(carReq, getApp());
        Car car = carRes.getCar();
        Bitmap carImage = BitmapFactory.decodeByteArray(car.getPhoto(), 0, car.getPhoto().length);

        // Setting the car image
        ((ImageView) findViewById(R.id.mapViewPickupImageViewCar)).setImageBitmap(carImage);

        // Setting the car name
        ((TextView) findViewById(R.id.mapViewPickupTextViewCarName)).setText("Car type: " + car.getCarName());

        // Setting the comfort
        ((RatingBar) findViewById(R.id.mapViewPickupAndDropoffComfortStars))
                .setRating((float) car.getComfort());

    } catch (ClientProtocolException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (IOException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (InterruptedException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    } catch (ExecutionException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Adding the date of ride
    Date d = journey.getStart().getTime();
    SimpleDateFormat sdfDate = new SimpleDateFormat("MMM dd yyyy");
    SimpleDateFormat sdfTime = new SimpleDateFormat("HH:mm zzz");
    String dateText = "Date: " + sdfDate.format(d);
    String timeText = "Time: " + sdfTime.format(d);
    ((TextView) findViewById(R.id.mapViewPickupTextViewDate)).setText(dateText + "\n" + timeText);

    //Adding Gender to the driver
    ImageView iv_image;
    iv_image = (ImageView) findViewById(R.id.gender);

    try {
        if (driver.getGender().equals("Male")) {
            Drawable male = getResources().getDrawable(R.drawable.male);
            iv_image.setImageDrawable(male);
        } else if (driver.getGender().equals("Female")) {
            Drawable female = getResources().getDrawable(R.drawable.female);
            iv_image.setImageDrawable(female);
        }
    } catch (NullPointerException e1) {
        // TODO Auto-generated catch block
        e1.printStackTrace();
    }

    // Initializing the two autocomplete textviews pickup and dropoff
    initAutocomplete();

    // Adding onClickListener for the button "Ask for a ride"
    btnSendRequest = (Button) findViewById(no.ntnu.idi.socialhitchhiking.R.id.mapViewPickupBtnSendRequest);
    btnSendRequest.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View v) {
            Response res;
            NotificationRequest req;

            if (pickupPoint == null || dropoffPoint == null) {
                //makeToast("You have to choose pickup point and dropoff point.");
                AlertDialog.Builder ad = new AlertDialog.Builder(MapActivityAddPickupAndDropoff.this);
                ad.setMessage("You have to choose pickup point and dropoff point.");
                ad.setTitle("Unable to send request");
                ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                    public void onClick(DialogInterface dialog, int id) {

                    }
                });
                ad.show();
                return;
            }

            inPickupMode = true;

            String senderID = getApp().getUser().getID();
            String recipientID = getApp().getSelectedJourney().getRoute().getOwner().getID();
            String senderName = getApp().getUser().getFullName();
            String comment = ((EditText) findViewById(R.id.mapViewPickupEtComment)).getText().toString();
            int journeyID = getApp().getSelectedJourney().getSerial();

            // Creating a new notification to be sendt to the driver
            Notification n = new Notification(senderID, recipientID, senderName, comment, journeyID,
                    NotificationType.HITCHHIKER_REQUEST, pickupPoint, dropoffPoint, Calendar.getInstance());
            req = new NotificationRequest(RequestType.SEND_NOTIFICATION, getApp().getUser(), n);

            // Sending notification
            try {
                res = RequestTask.sendRequest(req, getApp());
                if (res instanceof UserResponse) {
                    if (res.getStatus() == ResponseStatus.OK) {
                        makeToast("Ride request sent to driver");
                        finish();
                    }
                    if (res.getStatus() == ResponseStatus.FAILED) {
                        if (res.getErrorMessage().contains("no_duplicate_notifications")) {
                            //makeToast("You have already sent a request on this journey");
                            AlertDialog.Builder ad = new AlertDialog.Builder(
                                    MapActivityAddPickupAndDropoff.this);
                            ad.setMessage("You have already sent a request on this ride");
                            ad.setTitle("Unable to send request");
                            ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            ad.show();
                        } else if (res.getErrorMessage().equals("No available seats")) {
                            //makeToast("There are no available seats on this ride");
                            AlertDialog.Builder ad = new AlertDialog.Builder(
                                    MapActivityAddPickupAndDropoff.this);
                            ad.setMessage("There are no available seats on this ride");
                            ad.setTitle("Unable to send request");
                            ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            ad.show();
                        } else if (res.getErrorMessage().equals("User already in journey")) {
                            //makeToast("You have already hitched this ride");
                            AlertDialog.Builder ad = new AlertDialog.Builder(
                                    MapActivityAddPickupAndDropoff.this);
                            ad.setMessage("You have already hitched this ride");
                            ad.setTitle("Unable to send request");
                            ad.setPositiveButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface dialog, int id) {

                                }
                            });
                            ad.show();
                        } else {
                            makeToast("Could not send request");
                        }
                    }
                }
            } catch (ClientProtocolException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (IOException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (InterruptedException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            } catch (ExecutionException e) {
                // TODO Auto-generated catch block
                e.printStackTrace();
            }

        }
    });

    // Adding buttons where you choose between pickup point and dropoff point
    btnSelectPickupPoint = (Button) findViewById(R.id.mapViewPickupBtnPickup);
    btnSelectPickupPoint.setBackgroundColor(notSelected);
    btnSelectDropoffPoint = (Button) findViewById(R.id.mapViewPickupBtnDropoff);
    btnSelectDropoffPoint.setBackgroundColor(notSelected);
    // Setting the selected pickup point
    btnSelectPickupPoint.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            isSelectingDropoffPoint = false;
            isSelectingPickupPoint = true;
            btnSelectPickupPoint.setBackgroundColor(selected);
            btnSelectDropoffPoint.setBackgroundColor(notSelected);
            makeToast("Press the map to add pickup location");

        }
    });

    // Setting the selected dropoff point
    btnSelectDropoffPoint.setOnClickListener(new OnClickListener() {
        @Override
        public void onClick(View arg0) {
            isSelectingDropoffPoint = true;
            isSelectingPickupPoint = false;
            btnSelectPickupPoint.setBackgroundColor(notSelected);
            btnSelectDropoffPoint.setBackgroundColor(selected);
            makeToast("Press the map to add dropoff location");
        }
    });

    // Adding message to the user
    makeToast("Please set a pickup and dropoff location.");
}

From source file:com.gokuai.yunkuandroidsdk.imageutils.ImageWorker.java

/**
 * Called when the processing is complete and the final drawable should be
 * set on the ImageView.//from   www . java 2  s . co m
 *
 * @param imageView
 * @param drawable
 */
private void setImageDrawable(ImageView imageView, Drawable drawable) {
    if (mFadeInBitmap) {
        // Transition drawable with a transparent drawable and the final drawable
        final TransitionDrawable td = new TransitionDrawable(
                new Drawable[] { new ColorDrawable(android.R.color.transparent),
                        isRoundDrawable
                                ? new BitmapDrawable(mResources,
                                        Util.makeRoundDrawable(drawable, GKApplication.getInstance(), false))
                                : drawable });
        // Set background to loading bitmap
        imageView.setBackgroundDrawable(isRoundDrawable
                ? new BitmapDrawable(mResources,
                        Util.makeRoundDrawable(drawable, GKApplication.getInstance(), false))
                : new BitmapDrawable(mResources, mLoadingBitmap));

        imageView.setImageDrawable(td);
        td.startTransition(FADE_IN_TIME);
    } else {
        if (isRoundDrawable) {

            imageView.setImageBitmap(Util.makeRoundDrawable(drawable, GKApplication.getInstance(), false));
        } else {

            imageView.setImageDrawable(drawable);
        }
    }
}

From source file:cn.com.wo.bitmap.ImageWorker.java

public void loadImage(String url, ImageView imageView, boolean isBackground) {
    //      url = Images.getUrl();
    if (url == null || url.trim().length() == 0 || !url.startsWith("http"))
        return;//from  w ww .j a va  2s.co  m
    if (ImageFetcher.isDebug)
        Log.i(ImageFetcher.TAG, "loadImage " + url + "; isBg=" + isBackground);
    //    url = "http://58.254.132.169/picture/90755000/copyright/singer/2012032806/23280.jpg";

    BitmapDrawable value = null;

    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(url);
    }

    if (value != null) {
        // Bitmap found in memory cache
        if (isBackground)
            imageView.setBackgroundDrawable(value);
        else
            imageView.setImageDrawable(value);
    } else if (cancelPotentialWork(url, imageView, isBackground)) {
        imageView.setTag(0);
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView, 0, isBackground);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap[0], task);
        //          imageView.setImageDrawable(asyncDrawable);

        if (isBackground)
            imageView.setBackgroundDrawable(asyncDrawable);
        else
            imageView.setImageDrawable(asyncDrawable);

        // NOTE: This uses a custom version of AsyncTask that has been pulled from the
        // framework and slightly modified. Refer to the docs at the top of the class
        // for more info on what was changed.
        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, url);
    }
}

From source file:cn.com.wo.bitmap.ImageWorker.java

public void loadImage(String url, ImageView imageView, int radian, boolean isBackground) {
    if (url == null || url.trim().length() == 0 || !url.startsWith("http"))
        return;/*from   www  . j  ava  2s.  c  o m*/
    BitmapDrawable value = null;

    if (ImageFetcher.isDebug)
        Log.i(ImageFetcher.TAG, "loadImage " + url + "; isBg=" + isBackground);

    if (mImageCache != null) {
        value = mImageCache.getBitmapFromMemCache(String.valueOf(url));
    }

    if (value != null) {
        // Bitmap found in memory cache
        //            imageView.setImageDrawable(value);
        if (isBackground) {
            imageView.setBackgroundDrawable(null);
            imageView.setBackgroundDrawable(value);
        } else
            imageView.setImageDrawable(value);
    } else if (cancelPotentialWork(url, imageView, isBackground)) {
        imageView.setTag(0);
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView, radian, isBackground);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap[0], task);
        //            imageView.setImageDrawable(asyncDrawable);
        if (isBackground) {
            imageView.setBackgroundDrawable(null);
            imageView.setBackgroundDrawable(asyncDrawable);
        } else
            imageView.setImageDrawable(asyncDrawable);

        // NOTE: This uses a custom version of AsyncTask that has been pulled from the
        // framework and slightly modified. Refer to the docs at the top of the class
        // for more info on what was changed.
        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, url);
    }
}

From source file:com.farmerbb.taskbar.service.DashboardService.java

private void addPlaceholder(int cellId) {
    FrameLayout placeholder = (FrameLayout) cells.get(cellId).findViewById(R.id.placeholder);
    SharedPreferences pref = U.getSharedPreferences(this);
    String providerName = pref.getString("dashboard_widget_" + Integer.toString(cellId) + "_provider", "null");

    if (!providerName.equals("null")) {
        ImageView imageView = (ImageView) placeholder.findViewById(R.id.placeholder_image);
        ComponentName componentName = ComponentName.unflattenFromString(providerName);

        List<AppWidgetProviderInfo> providerInfoList = mAppWidgetManager
                .getInstalledProvidersForProfile(Process.myUserHandle());
        for (AppWidgetProviderInfo info : providerInfoList) {
            if (info.provider.equals(componentName)) {
                Drawable drawable = info.loadPreviewImage(this, -1);
                if (drawable == null)
                    drawable = info.loadIcon(this, -1);

                ColorMatrix matrix = new ColorMatrix();
                matrix.setSaturation(0);

                imageView.setImageDrawable(drawable);
                imageView.setColorFilter(new ColorMatrixColorFilter(matrix));
                break;
            }/*from w  w w .  j  ava 2s.c o  m*/
        }
    }

    placeholder.setVisibility(View.VISIBLE);
}

From source file:it.chefacile.app.MainActivity.java

protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    mContext = this;
    chefacileDb = new DatabaseHelper(this);
    // FilterButton = (ImageButton) findViewById(R.id.buttonfilter);
    TutorialButton = (ImageButton) findViewById(R.id.button);
    //  AddButton = (ImageButton) findViewById(R.id.button2);
    responseView = (TextView) findViewById(R.id.responseView);
    editText = (EditText) findViewById(R.id.ingredientText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);
    //Show = (ImageButton) findViewById(R.id.buttonShow);
    //Show2 = (ImageButton) findViewById(R.id.buttonShow2);
    materialAnimatedSwitch = (MaterialAnimatedSwitch) findViewById(R.id.pin);
    //buttoncuisine = (ImageButton) findViewById(R.id.btn_cuisine);
    //buttondiet = (ImageButton) findViewById(R.id.btn_diet);
    //buttonintol = (ImageButton) findViewById(R.id.btn_intoll);
    //Mostra = (Button) findViewById(R.id.btn_mostra);

    final Animation animation = new AlphaAnimation(1, 0); // Change alpha from fully visible to invisible
    animation.setDuration(1000); // duration - half a second
    animation.setInterpolator(new LinearInterpolator()); // do not alter animation rate
    animation.setRepeatCount(5); // Repeat animation infinitely
    animation.setRepeatMode(Animation.REVERSE);

    ImageView icon = new ImageView(this); // Create an icon
    icon.setImageDrawable(getResources().getDrawable(R.drawable.logo));

    final com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton actionButton = new com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton.Builder(
            this).setPosition(
                    com.oguzdev.circularfloatingactionmenu.library.FloatingActionButton.POSITION_RIGHT_CENTER)
                    .setContentView(icon).build();

    SubActionButton.Builder itemBuilder = new SubActionButton.Builder(this);
    // repeat many times:
    ImageView dietIcon = new ImageView(this);
    dietIcon.setImageDrawable(getResources().getDrawable(R.drawable.diet));
    SubActionButton button1 = itemBuilder.setContentView(dietIcon).build();
    button1.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showSingleChoiceDialogDiet(v);
        }//  w  ww.j  a  v  a2 s  . c  o m
    });

    ImageView intolIcon = new ImageView(this);
    intolIcon.setImageDrawable(getResources().getDrawable(R.drawable.intoll));
    SubActionButton button2 = itemBuilder.setContentView(intolIcon).build();
    button2.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showMultiChoiceDialogIntol(v);
        }
    });

    ImageView cuisineIcon = new ImageView(this);
    cuisineIcon.setImageDrawable(getResources().getDrawable(R.drawable.cook12));
    SubActionButton button3 = itemBuilder.setContentView(cuisineIcon).build();
    button3.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showMultiChoiceDialogCuisine(v);
        }
    });

    ImageView favouriteIcon = new ImageView(this);
    favouriteIcon.setImageDrawable(getResources().getDrawable(R.drawable.favorite));
    SubActionButton button4 = itemBuilder.setContentView(favouriteIcon).build();
    button4.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            showSimpleListDialogFav(v);
        }
    });

    ImageView wandIcon = new ImageView(this);
    wandIcon.setImageDrawable(getResources().getDrawable(R.drawable.wand));
    SubActionButton button5 = itemBuilder.setContentView(wandIcon).build();
    button5.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            sugg = getSuggestion();
            suggOccurrences = getCount();
            showSimpleListDialogSuggestions(v);
        }
    });

    final FloatingActionButton actionABC = (FloatingActionButton) findViewById(R.id.action_abc);

    actionABC.bringToFront();
    actionABC.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            if (ingredients.length() < 2) {
                Snackbar.make(responseView, "Insert at least one ingredient", Snackbar.LENGTH_LONG)
                        .setAction("Action", null).show();
            } else {
                new RetrieveFeedTask().execute();
            }
        }

        // Snackbar.make(view, "Non disponibile, mangia l'aria", Snackbar.LENGTH_LONG)
        //         .setAction("Action", null).show();

    });

    FloatingActionMenu actionMenu = new FloatingActionMenu.Builder(this).setStartAngle(90).setEndAngle(270)
            .addSubActionView(button1).addSubActionView(button2).addSubActionView(button3)
            .addSubActionView(button4).addSubActionView(button5).attachTo(actionButton).build();

    startDatabase(chefacileDb);

    for (int j = 0; j < cuisineItems.length; j++) {
        cuisineItems[j] = cuisineItems[j].substring(0, 1).toUpperCase() + cuisineItems[j].substring(1);
    }
    Arrays.sort(cuisineItems);

    for (int i = 0; i < 24; i++) {
        cuisineBool[i] = false;
    }

    Arrays.sort(intolItems);

    for (int i = 0; i < 11; i++) {
        intolBool[i] = false;
    }

    mListView = (MaterialListView) findViewById(R.id.material_listview);

    adapter = new ArrayAdapter<>(this, android.R.layout.simple_list_item_1);

    TutorialButton.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            startActivity(new Intent(MainActivity.this, IntroScreenActivity.class));
            overridePendingTransition(android.R.anim.fade_in, android.R.anim.fade_out);

        }
    });

    iv = (ImageView) findViewById(R.id.imageView);
    iv.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            clicks++;
            Log.d("CLICKS", String.valueOf(clicks));
            if (clicks == 15) {
                Log.d("IMAGE SHOWN", "mai vero");
                setBackground(iv);
            }
        }
    });

    materialAnimatedSwitch.setOnCheckedChangeListener(new MaterialAnimatedSwitch.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(boolean isChecked) {
            if (isChecked == true) {
                ranking = 2;
                Toast.makeText(getApplicationContext(), "Minimize missing ingredients", Toast.LENGTH_SHORT)
                        .show();
            } else {
                ranking = 1;
                Toast.makeText(getApplicationContext(), "Maximize used ingredients", Toast.LENGTH_SHORT).show();
            }
            Log.d("Ranking", String.valueOf(ranking));
        }
    });

    final CharSequence[] items = { "Maximize used ingredients", "Minimize missing ingredients" };

    editText.setOnKeyListener(new View.OnKeyListener() {
        public boolean onKey(View v, int keyCode, KeyEvent event) {
            if (event.getAction() == KeyEvent.ACTION_DOWN) {
                switch (keyCode) {
                case KeyEvent.KEYCODE_DPAD_CENTER:
                case KeyEvent.KEYCODE_ENTER:
                    if (!(editText.getText().toString().trim().equals(""))) {

                        String input;
                        String s1 = editText.getText().toString().substring(0, 1).toUpperCase();
                        String s2 = editText.getText().toString().substring(1);
                        input = s1 + s2;

                        Log.d("INPUT: ", input);
                        searchedIngredients.add(input);
                        Log.d("SEARCHED INGR LIST", searchedIngredients.toString());

                        if (!chefacileDb.findIngredientPREF(input)) {
                            if (chefacileDb.findIngredient(input)) {
                                chefacileDb.updateCount(input);
                                mapIngredients = chefacileDb.getDataInMapIngredient();
                                Map<String, Integer> map2;
                                map2 = sortByValue(mapIngredients);
                                Log.d("MAPPACOUNT: ", map2.toString());

                            } else {
                                if (chefacileDb.occursExceeded()) {
                                    //chefacileDb.deleteMinimum(input);
                                    // chefacileDb.insertDataIngredient(input);
                                    mapIngredients = chefacileDb.getDataInMapIngredient();
                                    Map<String, Integer> map3;
                                    map3 = sortByValue(mapIngredients);
                                    Log.d("MAPPAINGREDIENTE: ", map3.toString());

                                } else {
                                    chefacileDb.insertDataIngredient(input);
                                    mapIngredients = chefacileDb.getDataInMapIngredient();
                                    Map<String, Integer> map3;
                                    map3 = sortByValue(mapIngredients);
                                    Log.d("MAPPAINGREDIENTE: ", map3.toString());
                                }
                            }
                        }
                    }

                    if (editText.getText().toString().trim().equals("")) {
                        ingredients += editText.getText().toString().trim() + "";
                        editText.getText().clear();

                    } else {
                        ingredients += editText.getText().toString().replaceAll(" ", "+").trim().toLowerCase()
                                + ",";
                        singleIngredient = editText.getText().toString().trim().toLowerCase();
                        currentIngredient = singleIngredient;
                        new RetrieveIngredientTask().execute();

                        //adapter.add(singleIngredient.substring(0,1).toUpperCase() + singleIngredient.substring(1));
                    }

                    InputMethodManager in = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);

                    in.hideSoftInputFromWindow(editText.getApplicationWindowToken(),
                            InputMethodManager.HIDE_NOT_ALWAYS);

                    actionABC.startAnimation(animation);

                    return true;
                default:
                    break;
                }
            }
            return false;
        }
    });

    responseView = (TextView) findViewById(R.id.responseView);
    editText = (EditText) findViewById(R.id.ingredientText);
    progressBar = (ProgressBar) findViewById(R.id.progressBar);

}

From source file:android_network.hetnet.vpn_service.AdapterLog.java

@Override
public void bindView(final View view, final Context context, final Cursor cursor) {
    // Get values
    final long id = cursor.getLong(colID);
    long time = cursor.getLong(colTime);
    int version = (cursor.isNull(colVersion) ? -1 : cursor.getInt(colVersion));
    int protocol = (cursor.isNull(colProtocol) ? -1 : cursor.getInt(colProtocol));
    String flags = cursor.getString(colFlags);
    String saddr = cursor.getString(colSAddr);
    int sport = (cursor.isNull(colSPort) ? -1 : cursor.getInt(colSPort));
    String daddr = cursor.getString(colDAddr);
    int dport = (cursor.isNull(colDPort) ? -1 : cursor.getInt(colDPort));
    String dname = (cursor.isNull(colDName) ? null : cursor.getString(colDName));
    int uid = (cursor.isNull(colUid) ? -1 : cursor.getInt(colUid));
    String data = cursor.getString(colData);
    int allowed = (cursor.isNull(colAllowed) ? -1 : cursor.getInt(colAllowed));
    int connection = (cursor.isNull(colConnection) ? -1 : cursor.getInt(colConnection));
    int interactive = (cursor.isNull(colInteractive) ? -1 : cursor.getInt(colInteractive));

    // Get views/*from w  ww  . ja  v a2  s. com*/
    TextView tvTime = (TextView) view.findViewById(R.id.tvTime);
    TextView tvProtocol = (TextView) view.findViewById(R.id.tvProtocol);
    TextView tvFlags = (TextView) view.findViewById(R.id.tvFlags);
    TextView tvSAddr = (TextView) view.findViewById(R.id.tvSAddr);
    TextView tvSPort = (TextView) view.findViewById(R.id.tvSPort);
    final TextView tvDaddr = (TextView) view.findViewById(R.id.tvDAddr);
    TextView tvDPort = (TextView) view.findViewById(R.id.tvDPort);
    final TextView tvOrganization = (TextView) view.findViewById(R.id.tvOrganization);
    ImageView ivIcon = (ImageView) view.findViewById(R.id.ivIcon);
    TextView tvUid = (TextView) view.findViewById(R.id.tvUid);
    TextView tvData = (TextView) view.findViewById(R.id.tvData);
    ImageView ivConnection = (ImageView) view.findViewById(R.id.ivConnection);
    ImageView ivInteractive = (ImageView) view.findViewById(R.id.ivInteractive);

    // Show time
    tvTime.setText(new SimpleDateFormat("HH:mm:ss").format(time));

    // Show connection type
    if (connection <= 0)
        ivConnection.setImageResource(allowed > 0 ? R.drawable.host_allowed : R.drawable.host_blocked);
    else {
        if (allowed > 0)
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_on : R.drawable.other_on);
        else
            ivConnection.setImageResource(connection == 1 ? R.drawable.wifi_off : R.drawable.other_off);
    }
    if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
        Drawable wrap = DrawableCompat.wrap(ivConnection.getDrawable());
        DrawableCompat.setTint(wrap, allowed > 0 ? colorOn : colorOff);
    }

    // Show if screen on
    if (interactive <= 0)
        ivInteractive.setImageDrawable(null);
    else {
        ivInteractive.setImageResource(R.drawable.screen_on);
        if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP) {
            Drawable wrap = DrawableCompat.wrap(ivInteractive.getDrawable());
            DrawableCompat.setTint(wrap, colorOn);
        }
    }

    // Show protocol name
    tvProtocol.setText(Util.getProtocolName(protocol, version, false));

    // SHow TCP flags
    tvFlags.setText(flags);
    tvFlags.setVisibility(TextUtils.isEmpty(flags) ? View.GONE : View.VISIBLE);

    // Show source and destination port
    if (protocol == 6 || protocol == 17) {
        tvSPort.setText(sport < 0 ? "" : getKnownPort(sport));
        tvDPort.setText(dport < 0 ? "" : getKnownPort(dport));
    } else {
        tvSPort.setText(sport < 0 ? "" : Integer.toString(sport));
        tvDPort.setText(dport < 0 ? "" : Integer.toString(dport));
    }

    // Application icon
    ApplicationInfo info = null;
    PackageManager pm = context.getPackageManager();
    String[] pkg = pm.getPackagesForUid(uid);
    if (pkg != null && pkg.length > 0)
        try {
            info = pm.getApplicationInfo(pkg[0], 0);
        } catch (PackageManager.NameNotFoundException ignored) {
        }
    if (info == null)
        ivIcon.setImageDrawable(null);
    else if (info.icon == 0)
        Picasso.with(context).load(android.R.drawable.sym_def_app_icon).into(ivIcon);
    else {
        Uri uri = Uri.parse("android.resource://" + info.packageName + "/" + info.icon);
        Picasso.with(context).load(uri).resize(iconSize, iconSize).into(ivIcon);
    }

    // https://android.googlesource.com/platform/system/core/+/master/include/private/android_filesystem_config.h
    uid = uid % 100000; // strip off user ID
    if (uid == -1)
        tvUid.setText("");
    else if (uid == 0)
        tvUid.setText(context.getString(R.string.title_root));
    else if (uid == 9999)
        tvUid.setText("-"); // nobody
    else
        tvUid.setText(Integer.toString(uid));

    // Show source address
    tvSAddr.setText(getKnownAddress(saddr));

    // Show destination address
    if (resolve && !isKnownAddress(daddr))
        if (dname == null) {
            tvDaddr.setText(daddr);
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    ViewCompat.setHasTransientState(tvDaddr, true);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return InetAddress.getByName(args[0]).getHostName();
                    } catch (UnknownHostException ignored) {
                        return args[0];
                    }
                }

                @Override
                protected void onPostExecute(String name) {
                    tvDaddr.setText(">" + name);
                    ViewCompat.setHasTransientState(tvDaddr, false);
                }
            }.execute(daddr);
        } else
            tvDaddr.setText(dname);
    else
        tvDaddr.setText(getKnownAddress(daddr));

    // Show organization
    tvOrganization.setVisibility(View.GONE);
    if (organization) {
        if (!isKnownAddress(daddr))
            new AsyncTask<String, Object, String>() {
                @Override
                protected void onPreExecute() {
                    ViewCompat.setHasTransientState(tvOrganization, true);
                }

                @Override
                protected String doInBackground(String... args) {
                    try {
                        return Util.getOrganization(args[0]);
                    } catch (Throwable ex) {
                        Log.w(TAG, ex.toString() + "\n" + Log.getStackTraceString(ex));
                        return null;
                    }
                }

                @Override
                protected void onPostExecute(String organization) {
                    if (organization != null) {
                        tvOrganization.setText(organization);
                        tvOrganization.setVisibility(View.VISIBLE);
                    }
                    ViewCompat.setHasTransientState(tvOrganization, false);
                }
            }.execute(daddr);
    }

    // Show extra data
    if (TextUtils.isEmpty(data)) {
        tvData.setText("");
        tvData.setVisibility(View.GONE);
    } else {
        tvData.setText(data);
        tvData.setVisibility(View.VISIBLE);
    }
}

From source file:com.andreaszeiser.bob.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing
 * logic). A memory and disk cache will be used if an {@link ImageCache} has
 * been set using {@link ImageWorker#addImageCache}. If the image is found
 * in the memory cache, it is set immediately, otherwise an
 * {@link AsyncTask} will be created to asynchronously load the bitmap.
 * /*from w  w  w  .  j a v  a 2  s  .  com*/
 * @param data
 *            The URL of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 */
public void loadImage(Object data, ImageView imageView, Bitmap loadingBitmap, ImageWorkerListener listener) {
    Bitmap bitmap = null;

    if (data == null) {
        // no valid url, set loading image instead
        bitmap = loadingBitmap;
    }

    if (bitmap == null && mImageCache != null) {
        bitmap = mImageCache.getBitmapFromMemCache(String.valueOf(data));
    }

    if (bitmap != null) {
        // Bitmap found in memory cache
        if (listener == null || !listener.onImageLoaded(imageView, bitmap)) {
            imageView.setImageBitmap(bitmap);
        }
    } else if (cancelPotentialWork(data, imageView)) {
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView, listener);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, loadingBitmap, task);
        imageView.setImageDrawable(asyncDrawable);

        if (UIUtils.hasHoneycomb()) {
            // On HC+ we execute on a dual thread executor. There really
            // isn't much extra
            // benefit to having a really large pool of threads. Having more
            // than one will
            // likely benefit network bottlenecks though.
            task.executeOnExecutor(DUAL_THREAD_EXECUTOR, data);
        } else {
            // Otherwise pre-HC the default is a thread pool executor (not
            // ideal, serial
            // execution or a smaller number of threads would be better).
            task.execute(data);
        }
    }
}

From source file:android.support.asy.image.ImageWorker.java

/**
 * Load an image specified by the data parameter into an ImageView (override
 * {@link ImageWorker#processBitmap(Object)} to define the processing
 * logic). A memory and disk cache will be used if an {@link ImageCache} has
 * been set using {@link ImageWorker#setImageCache(ImageCache)}. If the
 * image is found in the memory cache, it is set immediately, otherwise an
 * {@link AsyncTask} will be created to asynchronously load the bitmap.
 * //from   w w  w  . j  a v  a 2s .co  m
 * @param data
 *            The URL of the image to download.
 * @param imageView
 *            The ImageView to bind the downloaded image to.
 */
public void loadImage(Object data, ImageView imageView) {

    if (TextUtils.isEmpty((String) data)) {
        return;
    }

    Bitmap bitmap = null;

    if (mImageCache != null) {
        bitmap = mImageCache.getBitmapFromMemCache(String.valueOf(data));
    }

    if (bitmap != null) {
        // Bitmap found in memory cache
        if ("fullscreen".equals(imageView.getTag())) {
            calculateImageViewHeight(String.valueOf(data), imageView);
        }
        imageView.setImageBitmap(bitmap);
    } else if (cancelPotentialWork(data, imageView)) { // imageview???false???imageview?true
        final BitmapWorkerTask task = new BitmapWorkerTask(imageView);
        final AsyncDrawable asyncDrawable = new AsyncDrawable(mResources, mLoadingBitmap, task);
        imageView.setImageDrawable(asyncDrawable);

        // NOTE: This uses a custom version of AsyncTask that has been
        // pulled from the
        // framework and slightly modified. Refer to the docs at the top of
        // the class
        // for more info on what was changed.
        task.executeOnExecutor(AsyncTask.DUAL_THREAD_EXECUTOR, data);
    }
}

From source file:com.elfec.cobranza.view.controls.SlidingTabLayout.java

private void populateTabStrip() {
    final PagerAdapter adapter = mViewPager.getAdapter();
    final View.OnClickListener tabClickListener = new TabClickListener();

    for (int i = 0; i < adapter.getCount(); i++) {
        View tabView = null;/*from  w  ww. ja  v  a  2s.c  o m*/
        TextView tabTitleView = null;
        ImageView tabIcon = null;
        if (mTabViewLayoutId != 0) {
            // If there is a custom tab view layout id set, try and inflate
            // it
            tabView = LayoutInflater.from(getContext()).inflate(mTabViewLayoutId, mTabStrip, false);
            tabTitleView = (TextView) tabView.findViewById(mTabViewTextViewId);
            if (mTabIconId != 0) {
                tabIcon = (ImageView) tabView.findViewById(mTabIconId);
            }
        }

        if (tabView == null) {
            tabView = createDefaultTabView(getContext());
        }

        if (tabTitleView == null && TextView.class.isInstance(tabView)) {
            tabTitleView = (TextView) tabView;
        }

        if (mDistributeEvenly) {
            LinearLayout.LayoutParams lp = (LinearLayout.LayoutParams) tabView.getLayoutParams();
            lp.width = 0;
            lp.weight = 1;
        }

        tabTitleView.setText(adapter.getPageTitle(i));
        if (tabIcon != null && (adapter instanceof IconTabProvider))
            tabIcon.setImageDrawable(
                    ContextCompat.getDrawable(getContext(), ((IconTabProvider) adapter).getPageIconResId(i)));
        tabView.setOnClickListener(tabClickListener);
        String desc = mContentDescriptions.get(i, null);
        if (desc != null) {
            tabView.setContentDescription(desc);
        }

        mTabStrip.addView(tabView);
        if (i == mViewPager.getCurrentItem()) {
            tabView.setSelected(true);
        }
    }
}