Example usage for android.widget ImageView ImageView

List of usage examples for android.widget ImageView ImageView

Introduction

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

Prototype

public ImageView(Context context) 

Source Link

Usage

From source file:com.cloudbase.cbhelperdemo.DataScreen.java

@SuppressWarnings("unchecked")
@Override/*from  w w w .  ja  va  2s  .c o m*/
public void handleResponse(CBQueuedRequest req, CBHelperResponse res) {
    // we are downloading a file
    if (res.getFunction().equals("download")) {
        if (res.getDownloadedFile() != null) {
            try {
                // resize the downloaded image and display it in an ImageView
                BitmapFactory.Options options = new BitmapFactory.Options();
                options.inJustDecodeBounds = true;
                BitmapFactory.decodeFile(res.getDownloadedFile().getAbsolutePath(), options);
                int imageHeight = options.outHeight;
                int imageWidth = options.outWidth;

                int reqWidth = 200;
                int reqHeight = 200;
                int inSampleSize = 1;

                if (imageHeight > reqHeight || imageWidth > reqWidth) {
                    if (imageWidth > imageHeight) {
                        inSampleSize = Math.round((float) imageHeight / (float) reqHeight);
                    } else {
                        inSampleSize = Math.round((float) imageWidth / (float) reqWidth);
                    }
                }
                options.inSampleSize = inSampleSize;

                options.inJustDecodeBounds = false;
                Bitmap myBitmap = BitmapFactory.decodeFile(res.getDownloadedFile().getAbsolutePath(), options); //BitmapFactory.decodeStream(new FileInputStream(res.getDownloadedFile()), options);

                ImageView imageView = new ImageView(this.getActivity());
                imageView.setImageBitmap(myBitmap);

                imageView.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        ((ViewGroup) v.getParent()).removeView(v);
                    }
                });
                //setting image position
                LayoutParams par = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
                imageView.setLayoutParams(par);
                this.getActivity().addContentView(imageView, par);

            } catch (Exception ex) {
                Log.e("DEMOAPP", "Error while opening downloaded file", ex);
            }
        }
    } else {
        if (res.getData() instanceof List) {
            // if we are not downloading and just running the search then read the array of result and
            // print the size.
            Log.d("DEMOAPP", "Is is array");
            AlertDialog.Builder builder = new AlertDialog.Builder(this.getActivity());
            builder.setTitle("Received response");
            builder.setMessage("total items: " + ((List<Object>) res.getData()).size());
            builder.setPositiveButton("OK", null);
            builder.show();
        } else {
            Log.d("DEMOAPP", "Data not array: " + res.getData().getClass().toString());
        }
    }

}

From source file:com.jgraves.achievementunlocked.AchievementsList_Fragment.java

private void addAchievementToList(Long id, String name, int points) {
    Log.i(ExploraApp.TAG, "Adding achievement image request of id " + id + " with height, " + imageViewHeight);
    FrameLayout fl = new FrameLayout(getActivity());
    touchMap.put(fl, id);/*w  w w . j  a  v a  2  s.  c  om*/
    fl.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            Long id = touchMap.get(v);
            Log.i(ExploraApp.TAG, "TOUCHED " + id);
            Intent intent = new Intent(getActivity(), Activity_AchievementInfo.class);
            intent.putExtra("achievement_id", Long.toString(id));
            startActivity(intent);
        }
    });
    TextView tv_name = new TextView(getActivity());
    TextView tv_points = new TextView(getActivity());
    ImageView iv = new ImageView(getActivity());
    fl.setMinimumHeight(imageViewHeight);
    fl.setMinimumWidth(ExploraApp.screenWidth);
    robotoTypeface = Typeface.createFromAsset(getActivity().getAssets(), "Roboto-Thin.ttf");
    tv_name.setText(name);
    tv_name.setTextSize(15f);
    tv_points.setTextSize(15f);
    tv_name.setTypeface(robotoTypeface);
    tv_points.setTypeface(robotoTypeface);
    tv_points.setText(Integer.toString(points));
    tv_points.setGravity(Gravity.RIGHT);
    tv_points.setTextColor(Color.WHITE);
    tv_name.setTextColor(Color.WHITE);
    iv.setMinimumHeight(imageViewHeight);
    iv.setMinimumWidth(ExploraApp.screenWidth);
    fl.addView(iv);
    fl.addView(tv_name);
    fl.addView(tv_points);
    ll_images_container.addView(fl);
    sv_images.bringChildToFront(mQuickReturnView);
    DefaultImageListener listener = new DefaultImageListener(iv);
    ImageRequest imageRequest = new ImageRequest(
            ExploraApp.url_main + "/achievement/" + id + "/photo?y=" + imageViewHeight + "&x="
                    + ExploraApp.screenWidth,
            listener, ExploraApp.screenWidth, imageViewHeight, Bitmap.Config.ARGB_8888, listener);
    ExploraApp.mRequestQueue.add(imageRequest);
}

From source file:com.thousandthoughts.tutorials.SensorFusionActivity.java

@Override
public void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.main);/*  w w w . jav  a 2s .c o m*/
    layout = (RelativeLayout) findViewById(R.id.mainlayout);
    IP1 = "";
    IP2 = "";
    angle1 = 0.0f;
    angle2 = 0.0f;
    gyroOrientation[0] = 0.0f;
    gyroOrientation[1] = 0.0f;
    gyroOrientation[2] = 0.0f;

    // initialise gyroMatrix with identity matrix
    gyroMatrix[0] = 1.0f;
    gyroMatrix[1] = 0.0f;
    gyroMatrix[2] = 0.0f;
    gyroMatrix[3] = 0.0f;
    gyroMatrix[4] = 1.0f;
    gyroMatrix[5] = 0.0f;
    gyroMatrix[6] = 0.0f;
    gyroMatrix[7] = 0.0f;
    gyroMatrix[8] = 1.0f;

    // get sensorManager and initialise sensor listeners
    mSensorManager = (SensorManager) this.getSystemService(SENSOR_SERVICE);
    initListeners();

    // wait for one second until gyroscope and magnetometer/accelerometer
    // data is initialised then scedule the complementary filter task
    fuseTimer.scheduleAtFixedRate(new calculateFusedOrientationTask(), 1000, TIME_CONSTANT);

    // GUI stuff
    try {
        client1 = new MyCoapClient(this.IP1);
        client2 = new MyCoapClient(this.IP2);
    } catch (UnknownHostException e) {
        // TODO Auto-generated catch block
        e.printStackTrace();
    }
    json = new JSONObject();
    mHandler = new Handler();
    radioSelection = 0;
    d.setRoundingMode(RoundingMode.HALF_UP);
    d.setMaximumFractionDigits(3);
    d.setMinimumFractionDigits(3);

    /// Application layout here only

    RelativeLayout.LayoutParams left = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams right = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams up = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams down = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams button1 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams button2 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams text1 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    RelativeLayout.LayoutParams text2 = new RelativeLayout.LayoutParams(
            android.view.ViewGroup.LayoutParams.WRAP_CONTENT, android.view.ViewGroup.LayoutParams.WRAP_CONTENT);
    ImageView img_left = new ImageView(this);
    ImageView img_right = new ImageView(this);
    ImageView img_up = new ImageView(this);
    ImageView img_down = new ImageView(this);
    ImageView img_button1 = new ImageView(this);
    ImageView img_button2 = new ImageView(this);
    final EditText edittext1 = new EditText(this);
    final EditText edittext2 = new EditText(this);
    img_left.setImageResource(R.drawable.left_button);
    img_right.setImageResource(R.drawable.right_button);
    img_up.setImageResource(R.drawable.up);
    img_down.setImageResource(R.drawable.down);
    img_button1.setImageResource(R.drawable.button);
    img_button2.setImageResource(R.drawable.button);

    left.setMargins(0, 66, 0, 0);
    right.setMargins(360, 66, 0, 0);
    up.setMargins(240, 90, 0, 0);
    down.setMargins(240, 240, 0, 0);
    button1.setMargins(440, 800, 0, 0);
    button2.setMargins(440, 900, 0, 0);
    text1.setMargins(5, 800, 0, 0);
    text2.setMargins(5, 900, 0, 0);

    layout.addView(img_left, left);
    layout.addView(img_right, right);
    layout.addView(img_up, up);
    layout.addView(img_down, down);
    layout.addView(img_button1, button1);
    layout.addView(edittext1, text1);
    layout.addView(img_button2, button2);
    layout.addView(edittext2, text2);

    img_left.getLayoutParams().height = 560;
    img_left.getLayoutParams().width = 280;
    img_right.getLayoutParams().height = 560;
    img_right.getLayoutParams().width = 280;
    img_up.getLayoutParams().height = 150;
    img_up.getLayoutParams().width = 150;
    img_down.getLayoutParams().height = 150;
    img_down.getLayoutParams().width = 150;
    img_button1.getLayoutParams().height = 100;
    img_button1.getLayoutParams().width = 200;
    edittext1.getLayoutParams().width = 400;
    edittext1.setText("84.248.76.84");
    edittext2.setText("84.248.76.84");
    img_button2.getLayoutParams().height = 100;
    img_button2.getLayoutParams().width = 200;
    edittext2.getLayoutParams().width = 400;

    /////////// Define and Remember Position for EACH PHYSICAL OBJECTS (LAPTOPS) /////////////////////
    img_button1.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // POSITION OF LAPTOP 1 IS REMEMBERED
                angle1 = fusedOrientation[0];
                IP1 = edittext1.getText().toString();
                try {
                    // CREATE CLIENT CONNECT TO FIRST LAPTOP
                    client1 = new MyCoapClient(IP1);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                //view.setImageResource(R.drawable.left_button);
                break;
            }
            return true;
        }

    });

    img_button2.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View view, MotionEvent event) {
            // TODO Auto-generated method stub
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                // POSITION OF LAPTOP 2 IS REMEMBERED
                angle2 = fusedOrientation[0];
                IP2 = edittext2.getText().toString();
                try {
                    // CREATE CLIENT CONNECT TO SECOND LAPTOP
                    client2 = new MyCoapClient(IP2);
                } catch (UnknownHostException e) {
                    // TODO Auto-generated catch block
                    e.printStackTrace();
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                break;
            }
            return true;
        }

    });

    img_left.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.left_button_press);

                ///////////////////// PERFORM CLICK ACTION BASED ON POSITION OF 2 PHYSICAL OBJECTS (LAPTOPs) HERE/////////////////////////

                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0 < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0) {
                        client1.runClient("left pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0 < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0) {
                        client2.runClient("left pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.left_button);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("left released");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("left released");
                    }
                }
                break;
            }
            return true;
        }
    });

    img_right.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.right_button_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("right pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("right pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.right_button);
                break;
            }
            return true;
        }
    });

    img_up.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.up_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("up pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("up pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.up);
                break;
            }
            return true;
        }
    });

    img_down.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            ImageView view = (ImageView) v;
            switch (event.getAction()) {
            case MotionEvent.ACTION_DOWN:
                view.setImageResource(R.drawable.down_press);
                // PHONE's ANGLE WITHIN FIRST LAPTOP//
                if (angle1 != 0.0f) {
                    if (angle1 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle1 * 180 / Math.PI + 40.0f) {
                        client1.runClient("down pressed");
                    }
                }
                //PHONE's ANGLE WITHIN SECOND LAPTOP//
                if (angle2 != 0.0f) {
                    if (angle2 * 180 / Math.PI - 40.0f < fusedOrientation[0] * 180 / Math.PI
                            && fusedOrientation[0] * 180 / Math.PI < angle2 * 180 / Math.PI + 40.0f) {
                        client2.runClient("down pressed");
                    }
                }
                break;
            case MotionEvent.ACTION_MOVE:
                break;
            case MotionEvent.ACTION_UP:
                view.setImageResource(R.drawable.down);
                break;
            }
            return true;
        }
    });
}

From source file:com.inter.trade.view.slideplayview.AbSlidingPlayView.java

/**
 * .//from   w  w  w. j  a v a 2s .co m
 */
public void creatIndex() {
    //?
    pageLineLayout.removeAllViews();
    mPageLineLayoutParent.setHorizontalGravity(pageLineHorizontalGravity);
    pageLineLayout.setGravity(Gravity.CENTER);
    pageLineLayout.setVisibility(View.VISIBLE);
    count = mListViews.size();
    for (int j = 0; j < count; j++) {
        ImageView imageView = new ImageView(context);
        pageLineLayoutParams.setMargins(5, 5, 5, 5);
        imageView.setLayoutParams(pageLineLayoutParams);
        if (j == 0) {
            imageView.setImageBitmap(displayImage);
        } else {
            imageView.setImageBitmap(hideImage);
        }
        pageLineLayout.addView(imageView, j);
    }
}

From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {//w  w  w.  j a  v  a 2s  .  c o m
        final HttpClient httpClient = ((HttpChanModule) MainApplication.getInstance().getChanModule(chanName))
                .getHttpClient();
        final String usingURL = scheme + RECAPTCHA_FALLBACK_URL + publicKey
                + (sToken != null && sToken.length() > 0 ? ("&stoken=" + sToken) : "");
        String refererURL = baseUrl != null && baseUrl.length() > 0 ? baseUrl : usingURL;
        Header[] customHeaders = new Header[] { new BasicHeader(HttpHeaders.REFERER, refererURL) };
        String htmlChallenge;
        if (lastChallenge != null && lastChallenge.getLeft().equals(usingURL)) {
            htmlChallenge = lastChallenge.getRight();
        } else {
            htmlChallenge = HttpStreamer.getInstance().getStringFromUrl(usingURL,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task, false);
        }
        lastChallenge = null;

        Matcher challengeMatcher = Pattern.compile("name=\"c\" value=\"([\\w-]+)").matcher(htmlChallenge);
        if (challengeMatcher.find()) {
            final String challenge = challengeMatcher.group(1);
            HttpResponseModel responseModel = HttpStreamer.getInstance().getFromUrl(
                    scheme + RECAPTCHA_IMAGE_URL + challenge + "&k=" + publicKey,
                    HttpRequestModel.builder().setGET().setCustomHeaders(customHeaders).build(), httpClient,
                    null, task);
            try {
                InputStream imageStream = responseModel.stream;
                final Bitmap challengeBitmap = BitmapFactory.decodeStream(imageStream);

                final String message;
                Matcher messageMatcher = Pattern.compile("imageselect-message(?:.*?)>(.*?)</div>")
                        .matcher(htmlChallenge);
                if (messageMatcher.find())
                    message = RegexUtils.removeHtmlTags(messageMatcher.group(1));
                else
                    message = null;

                final Bitmap candidateBitmap;
                Matcher candidateMatcher = Pattern
                        .compile("fbc-imageselect-candidates(?:.*?)src=\"data:image/(?:.*?);base64,([^\"]*)\"")
                        .matcher(htmlChallenge);
                if (candidateMatcher.find()) {
                    Bitmap bmp = null;
                    try {
                        byte[] imgData = Base64.decode(candidateMatcher.group(1), Base64.DEFAULT);
                        bmp = BitmapFactory.decodeByteArray(imgData, 0, imgData.length);
                    } catch (Exception e) {
                    }
                    candidateBitmap = bmp;
                } else
                    candidateBitmap = null;

                activity.runOnUiThread(new Runnable() {
                    final int maxX = 3;
                    final int maxY = 3;
                    final boolean[] isSelected = new boolean[maxX * maxY];

                    @SuppressLint("InlinedApi")
                    @Override
                    public void run() {
                        LinearLayout rootLayout = new LinearLayout(activity);
                        rootLayout.setOrientation(LinearLayout.VERTICAL);

                        if (candidateBitmap != null) {
                            ImageView candidateView = new ImageView(activity);
                            candidateView.setImageBitmap(candidateBitmap);
                            int picSize = (int) (activity.getResources().getDisplayMetrics().density * 50
                                    + 0.5f);
                            candidateView.setLayoutParams(new LinearLayout.LayoutParams(picSize, picSize));
                            candidateView.setScaleType(ImageView.ScaleType.FIT_XY);
                            rootLayout.addView(candidateView);
                        }

                        if (message != null) {
                            TextView textView = new TextView(activity);
                            textView.setText(message);
                            CompatibilityUtils.setTextAppearance(textView, android.R.style.TextAppearance);
                            textView.setLayoutParams(
                                    new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                            LinearLayout.LayoutParams.WRAP_CONTENT));
                            rootLayout.addView(textView);
                        }

                        FrameLayout frame = new FrameLayout(activity);
                        frame.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));

                        final ImageView imageView = new ImageView(activity);
                        imageView.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        imageView.setScaleType(ImageView.ScaleType.FIT_XY);
                        imageView.setImageBitmap(challengeBitmap);
                        frame.addView(imageView);

                        final LinearLayout selector = new LinearLayout(activity);
                        selector.setLayoutParams(new FrameLayout.LayoutParams(
                                FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT));
                        AppearanceUtils.callWhenLoaded(imageView, new Runnable() {
                            @Override
                            public void run() {
                                selector.setLayoutParams(new FrameLayout.LayoutParams(imageView.getWidth(),
                                        imageView.getHeight()));
                            }
                        });
                        selector.setOrientation(LinearLayout.VERTICAL);
                        selector.setWeightSum(maxY);
                        for (int y = 0; y < maxY; ++y) {
                            LinearLayout subSelector = new LinearLayout(activity);
                            subSelector.setLayoutParams(new LinearLayout.LayoutParams(
                                    LinearLayout.LayoutParams.MATCH_PARENT, 0, 1f));
                            subSelector.setOrientation(LinearLayout.HORIZONTAL);
                            subSelector.setWeightSum(maxX);
                            for (int x = 0; x < maxX; ++x) {
                                FrameLayout switcher = new FrameLayout(activity);
                                switcher.setLayoutParams(new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.MATCH_PARENT, 1f));
                                switcher.setTag(new int[] { x, y });
                                switcher.setOnClickListener(new View.OnClickListener() {
                                    @Override
                                    public void onClick(View v) {
                                        int[] coord = (int[]) v.getTag();
                                        int index = coord[1] * maxX + coord[0];
                                        isSelected[index] = !isSelected[index];
                                        v.setBackgroundColor(isSelected[index] ? Color.argb(128, 0, 255, 0)
                                                : Color.TRANSPARENT);
                                    }
                                });
                                subSelector.addView(switcher);
                            }
                            selector.addView(subSelector);
                        }

                        frame.addView(selector);
                        rootLayout.addView(frame);

                        Button checkButton = new Button(activity);
                        checkButton.setLayoutParams(
                                new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT));
                        checkButton.setText(android.R.string.ok);
                        rootLayout.addView(checkButton);

                        ScrollView dlgView = new ScrollView(activity);
                        dlgView.addView(rootLayout);

                        final Dialog dialog = new Dialog(activity);
                        dialog.setTitle("Recaptcha");
                        dialog.setContentView(dlgView);
                        dialog.setCanceledOnTouchOutside(false);
                        dialog.setOnCancelListener(new DialogInterface.OnCancelListener() {
                            @Override
                            public void onCancel(DialogInterface dialog) {
                                if (!task.isCancelled()) {
                                    callback.onError("Cancelled");
                                }
                            }
                        });
                        dialog.getWindow().setLayout(ViewGroup.LayoutParams.MATCH_PARENT,
                                ViewGroup.LayoutParams.WRAP_CONTENT);
                        dialog.show();

                        checkButton.setOnClickListener(new View.OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                dialog.dismiss();
                                if (task.isCancelled())
                                    return;
                                Async.runAsync(new Runnable() {
                                    @Override
                                    public void run() {
                                        try {
                                            List<NameValuePair> pairs = new ArrayList<NameValuePair>();
                                            pairs.add(new BasicNameValuePair("c", challenge));
                                            for (int i = 0; i < isSelected.length; ++i)
                                                if (isSelected[i])
                                                    pairs.add(new BasicNameValuePair("response",
                                                            Integer.toString(i)));

                                            HttpRequestModel request = HttpRequestModel.builder()
                                                    .setPOST(new UrlEncodedFormEntity(pairs, "UTF-8"))
                                                    .setCustomHeaders(new Header[] {
                                                            new BasicHeader(HttpHeaders.REFERER, usingURL) })
                                                    .build();
                                            String response = HttpStreamer.getInstance().getStringFromUrl(
                                                    usingURL, request, httpClient, null, task, false);
                                            String hash = "";
                                            Matcher matcher = Pattern.compile(
                                                    "fbc-verification-token(?:.*?)<textarea[^>]*>([^<]*)<",
                                                    Pattern.DOTALL).matcher(response);
                                            if (matcher.find())
                                                hash = matcher.group(1);

                                            if (hash.length() > 0) {
                                                Recaptcha2solved.push(publicKey, hash);
                                                activity.runOnUiThread(new Runnable() {
                                                    @Override
                                                    public void run() {
                                                        callback.onSuccess();
                                                    }
                                                });
                                            } else {
                                                lastChallenge = Pair.of(usingURL, response);
                                                throw new RecaptchaException(
                                                        "incorrect answer (hash is empty)");
                                            }
                                        } catch (final Exception e) {
                                            Logger.e(TAG, e);
                                            if (task.isCancelled())
                                                return;
                                            handle(activity, task, callback);
                                        }
                                    }
                                });
                            }
                        });
                    }
                });
            } finally {
                responseModel.release();
            }
        } else
            throw new Exception("can't parse recaptcha challenge answer");
    } catch (final Exception e) {
        Logger.e(TAG, e);
        if (!task.isCancelled()) {
            activity.runOnUiThread(new Runnable() {
                @Override
                public void run() {
                    callback.onError(e.getMessage() != null ? e.getMessage() : e.toString());
                }
            });
        }
    }
}

From source file:eu.geopaparazzi.library.forms.views.GPictureView.java

public void refresh(final Context context) throws Exception {
    log("Entering refresh....");

    if (_value != null && _value.length() > 0) {
        String[] imageSplit = _value.split(IMAGE_ID_SEPARATOR);
        log("Handling images: " + _value);

        IImagesDbHelper imagesDbHelper = DefaultHelperClasses.getDefaulfImageHelper();

        for (String imageId : imageSplit) {
            log("img: " + imageId);

            if (imageId.length() == 0) {
                continue;
            }//from  w  ww  . java2  s.co  m
            long imageIdLong;
            try {
                imageIdLong = Long.parseLong(imageId);
            } catch (Exception e) {
                continue;
            }
            if (addedImages.contains(imageId.trim())) {
                continue;
            }

            byte[] imageThumbnail = imagesDbHelper.getImageThumbnail(imageIdLong);
            Bitmap thumbnail = ImageUtilities.getImageFromImageData(imageThumbnail);

            ImageView imageView = new ImageView(context);
            imageView.setLayoutParams(new LinearLayout.LayoutParams(102, 102));
            imageView.setPadding(5, 5, 5, 5);
            imageView.setImageBitmap(thumbnail);
            imageView.setBackgroundDrawable(getResources().getDrawable(R.drawable.border_black_1px));
            //                imageView.setOnClickListener(new View.OnClickListener() {
            //                    public void onClick(View v) {
            //                        /*
            //                         * open in markers to edit it
            //                         */
            //                        // FIXME
            //                        MarkersUtilities.launchOnImage(context, image);
            //                        // Intent intent = new Intent();
            //                        // intent.setAction(android.content.Intent.ACTION_VIEW);
            //                        //                        intent.setDataAndType(Uri.fromFile(image), "image/*"); //$NON-NLS-1$
            //                        // context.startActivity(intent);
            //                    }
            //                });
            log("Creating thumb and adding it: " + imageId);
            imageLayout.addView(imageView);
            imageLayout.invalidate();
            addedImages.add(imageId);
        }

        if (addedImages.size() > 0) {
            StringBuilder sb = new StringBuilder();
            for (String imagePath : addedImages) {
                sb.append(IMAGE_ID_SEPARATOR).append(imagePath);
            }
            _value = sb.substring(1);

            log("New img ids: " + _value);

        }
        log("Exiting refresh....");

    }
}

From source file:org.dmfs.android.view.DrawablePagerTitleStrip.java

void updateAdapter(PagerAdapter oldAdapter, PagerAdapter newAdapter) {
    if (oldAdapter != null) {
        oldAdapter.unregisterDataSetObserver(mPageListener);
        mWatchingAdapter = null;/* w  ww .j  av  a2  s  .  c  om*/
    }
    if (newAdapter != null) {
        if (!(newAdapter instanceof IDrawableTitlePagerAdapter)) {
            throw new IllegalArgumentException("Adapter must implement IDrawableTitlePagerAdapter");
        }

        newAdapter.registerDataSetObserver(mPageListener);
        mWatchingAdapter = new WeakReference<PagerAdapter>(newAdapter);

        Context context = getContext();

        // TODO: we should determine the number of images dynamically
        int newCount = Math.max(1, Math.min(9, newAdapter.getCount()));

        if (mImageViews == null || mImageViews.length < newCount) {
            ImageView[] newImages = new ImageView[newCount];
            int start = 0;
            if (mImageViews != null) {
                System.arraycopy(mImageViews, 0, newImages, 0, mImageViews.length);
                start = mImageViews.length;
            }

            for (int i = start; i < newCount; ++i) {
                addView(newImages[i] = new ImageView(context));
            }
            mImageViews = newImages;
        } else if (mImageViews.length > newCount) {
            ImageView[] newImages = new ImageView[newCount];
            System.arraycopy(mImageViews, 0, newImages, 0, newCount);

            for (int i = newCount; i < mImageViews.length; ++i) {
                removeView(mImageViews[i]);
            }

            mImageViews = newImages;
        }
    } else {
        mImageViews = null;
    }

    if (mPager != null) {
        mLastKnownCurrentPage = -1;
        mLastKnownPositionOffset = -1;
        updateImages(mPager.getCurrentItem(), newAdapter);
        requestLayout();
    }
}

From source file:com.app.sample.chatting.widget.PagerSlidingTabStrip.java

public void notifyDataSetChanged() {

    tabsContainer.removeAllViews();/*from   w  ww .ja v  a2  s .c om*/

    tabCount = pager.getAdapter().getCount();

    for (int i = 0; i < tabCount; i++) {
        if (pager.getAdapter() instanceof IconTabProvider) {
            ImageView image = new ImageView(getContext());
            ((IconTabProvider) pager.getAdapter()).setPageIcon(i, image);
            addTab(i, image);
        } else {
            addTextTab(i, pager.getAdapter().getPageTitle(i).toString());
        }
    }

    updateTabStyles();

    getViewTreeObserver().addOnGlobalLayoutListener(new OnGlobalLayoutListener() {

        @SuppressWarnings("deprecation")
        @SuppressLint("NewApi")
        @Override
        public void onGlobalLayout() {

            if (Build.VERSION.SDK_INT < Build.VERSION_CODES.JELLY_BEAN) {
                getViewTreeObserver().removeGlobalOnLayoutListener(this);
            } else {
                getViewTreeObserver().removeOnGlobalLayoutListener(this);
            }

            currentPosition = pager.getCurrentItem();
            scrollToChild(currentPosition, 0);
        }
    });

}

From source file:com.userhook.view.UHMessageView.java

protected void loadMessage(Map<String, Object> params) {

    if (meta.getDisplayType().equals(UHMessageMeta.TYPE_IMAGE)) {

        if (meta.getButton1() != null && meta.getButton1().getImage() != null
                && meta.getButton1().getImage().getUrl() != null) {

            AsyncTask task = new AsyncTask<Object, Void, Drawable>() {

                @Override//from   w  ww.  j a va 2  s .c  o m
                protected Drawable doInBackground(Object... params) {
                    Drawable drawable = null;

                    try {

                        URL url = new URL((String) params[0]);

                        HttpURLConnection conn = (HttpURLConnection) url.openConnection();
                        InputStream is = conn.getInputStream();

                        drawable = Drawable.createFromStream(is, "src");

                        int height = drawable.getIntrinsicHeight();
                        int width = drawable.getIntrinsicWidth();

                        drawable.setBounds(0, 0, width, height);

                    } catch (Exception e) {
                        Log.e(UserHook.TAG, "error download message image", e);
                    }

                    return drawable;
                }

                @Override
                protected void onPostExecute(Drawable result) {

                    if (result != null) {

                        // size image to fit inside the view
                        int screenHeight = getResources().getDisplayMetrics().heightPixels;
                        int screenWidth = getResources().getDisplayMetrics().widthPixels;

                        int heightGutter = 40;
                        int widthGutter = 40;

                        int screenSpaceHeight = screenHeight - heightGutter * 2;
                        int screenSpaceWidth = screenWidth - widthGutter * 2;

                        float height = result.getIntrinsicHeight();
                        float width = result.getIntrinsicWidth();
                        float aspect = height / width;

                        if (height > screenSpaceHeight) {
                            height = screenHeight;
                            width = height / aspect;
                        }

                        if (width > screenSpaceWidth) {
                            width = screenSpaceWidth;
                            height = width * aspect;
                        }

                        ImageView imageView = new ImageView(getContext());
                        imageView.setScaleType(ImageView.ScaleType.CENTER_INSIDE);
                        imageView.setImageDrawable(result);

                        LayoutParams layoutParams = new LayoutParams((int) width, (int) height);
                        layoutParams.addRule(CENTER_IN_PARENT);
                        addView(imageView, layoutParams);

                        // add click handler to image
                        imageView.setOnClickListener(new OnClickListener() {
                            @Override
                            public void onClick(View v) {
                                if (meta.getButton1() != null) {
                                    clickedButton(meta.getButton1());
                                }
                            }
                        });

                        contentLoaded = true;

                        if (showAfterLoad) {
                            showDialog();
                        }

                    }
                }
            };

            task.execute(meta.getButton1().getImage().getUrl());

        }

    } else if (UHMessageTemplate.getInstance().hasTemplate(meta.getDisplayType())) {

        String html = UHMessageTemplate.getInstance().renderTemplate(meta);

        loadWebViewContent(html);

        if (showAfterLoad) {
            showDialog();
        }

    } else {

        UHPostAsyncTask asyncTask = new UHPostAsyncTask(params, new UHAsyncTask.UHAsyncTaskListener() {
            @Override
            public void onSuccess(String result) {

                if (result != null) {

                    loadWebViewContent(result);

                }

                if (showAfterLoad) {
                    showDialog();
                }
            }
        });

        asyncTask.execute(UserHook.UH_HOST_URL + UH_MESSAGE_PATH);

    }

}

From source file:net.bluehack.ui.WallpapersActivity.java

@Override
public View createView(Context context) {
    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);
    actionBar.setTitle(LocaleController.getString("ChatBackground", R.string.ChatBackground));
    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {
        @Override/*ww w.jav a2 s .c o  m*/
        public void onItemClick(int id) {
            if (id == -1) {
                finishFragment();
            } else if (id == done_button) {
                boolean done;
                TLRPC.WallPaper wallPaper = wallpappersByIds.get(selectedBackground);
                if (wallPaper != null && wallPaper.id != 1000001 && wallPaper instanceof TLRPC.TL_wallPaper) {
                    int width = AndroidUtilities.displaySize.x;
                    int height = AndroidUtilities.displaySize.y;
                    if (width > height) {
                        int temp = width;
                        width = height;
                        height = temp;
                    }
                    TLRPC.PhotoSize size = FileLoader.getClosestPhotoSizeWithSize(wallPaper.sizes,
                            Math.min(width, height));
                    String fileName = size.location.volume_id + "_" + size.location.local_id + ".jpg";
                    File f = new File(FileLoader.getInstance().getDirectory(FileLoader.MEDIA_DIR_CACHE),
                            fileName);
                    File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg");
                    try {
                        done = AndroidUtilities.copyFile(f, toFile);
                    } catch (Exception e) {
                        done = false;
                        FileLog.e("tmessages", e);
                    }
                } else {
                    if (selectedBackground == -1) {
                        File fromFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper-temp.jpg");
                        File toFile = new File(ApplicationLoader.getFilesDirFixed(), "wallpaper.jpg");
                        done = fromFile.renameTo(toFile);
                    } else {
                        done = true;
                    }
                }

                if (done) {
                    SharedPreferences preferences = ApplicationLoader.applicationContext
                            .getSharedPreferences("mainconfig", Activity.MODE_PRIVATE);
                    SharedPreferences.Editor editor = preferences.edit();
                    editor.putInt("selectedBackground", selectedBackground);
                    editor.putInt("selectedColor", selectedColor);
                    editor.commit();
                    ApplicationLoader.reloadWallpaper();
                }
                finishFragment();
            }
        }
    });

    ActionBarMenu menu = actionBar.createMenu();
    doneButton = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));

    FrameLayout frameLayout = new FrameLayout(context);
    fragmentView = frameLayout;

    backgroundImage = new ImageView(context);
    backgroundImage.setScaleType(ImageView.ScaleType.CENTER_CROP);
    frameLayout.addView(backgroundImage,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));
    backgroundImage.setOnTouchListener(new View.OnTouchListener() {
        @Override
        public boolean onTouch(View v, MotionEvent event) {
            return true;
        }
    });

    progressView = new FrameLayout(context);
    progressView.setVisibility(View.INVISIBLE);
    frameLayout.addView(progressView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT,
            LayoutHelper.MATCH_PARENT, Gravity.TOP | Gravity.LEFT, 0, 0, 0, 52));

    progressViewBackground = new View(context);
    progressViewBackground.setBackgroundResource(R.drawable.system_loader);
    progressView.addView(progressViewBackground, LayoutHelper.createFrame(36, 36, Gravity.CENTER));

    ProgressBar progressBar = new ProgressBar(context);
    try {
        progressBar.setIndeterminateDrawable(context.getResources().getDrawable(R.drawable.loading_animation));
    } catch (Exception e) {
        //don't promt
    }
    progressBar.setIndeterminate(true);
    AndroidUtilities.setProgressBarAnimationDuration(progressBar, 1500);
    progressView.addView(progressBar, LayoutHelper.createFrame(32, 32, Gravity.CENTER));

    RecyclerListView listView = new RecyclerListView(context);
    listView.setClipToPadding(false);
    listView.setTag(8);
    listView.setPadding(AndroidUtilities.dp(40), 0, AndroidUtilities.dp(40), 0);
    LinearLayoutManager layoutManager = new LinearLayoutManager(context);
    layoutManager.setOrientation(LinearLayoutManager.HORIZONTAL);
    listView.setLayoutManager(layoutManager);
    listView.setDisallowInterceptTouchEvents(true);
    listView.setOverScrollMode(RecyclerListView.OVER_SCROLL_NEVER);
    listView.setAdapter(listAdapter = new ListAdapter(context));
    frameLayout.addView(listView,
            LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 102, Gravity.LEFT | Gravity.BOTTOM));
    listView.setOnItemClickListener(new RecyclerListView.OnItemClickListener() {
        @Override
        public void onItemClick(View view, int position) {
            if (position == 0) {
                if (getParentActivity() == null) {
                    return;
                }
                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());

                CharSequence[] items = new CharSequence[] {
                        LocaleController.getString("FromCamera", R.string.FromCamera),
                        LocaleController.getString("FromGalley", R.string.FromGalley),
                        LocaleController.getString("Cancel", R.string.Cancel) };

                builder.setItems(items, new DialogInterface.OnClickListener() {
                    @Override
                    public void onClick(DialogInterface dialogInterface, int i) {
                        try {
                            if (i == 0) {
                                Intent takePictureIntent = new Intent(MediaStore.ACTION_IMAGE_CAPTURE);
                                File image = AndroidUtilities.generatePicturePath();
                                if (image != null) {
                                    if (Build.VERSION.SDK_INT >= 24) {
                                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                FileProvider.getUriForFile(getParentActivity(),
                                                        BuildConfig.APPLICATION_ID + ".provider", image));
                                        takePictureIntent.addFlags(Intent.FLAG_GRANT_WRITE_URI_PERMISSION);
                                        takePictureIntent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION);
                                    } else {
                                        takePictureIntent.putExtra(MediaStore.EXTRA_OUTPUT,
                                                Uri.fromFile(image));
                                    }
                                    currentPicturePath = image.getAbsolutePath();
                                }
                                startActivityForResult(takePictureIntent, 10);
                            } else if (i == 1) {
                                Intent photoPickerIntent = new Intent(Intent.ACTION_PICK);
                                photoPickerIntent.setType("image/*");
                                startActivityForResult(photoPickerIntent, 11);
                            }
                        } catch (Exception e) {
                            FileLog.e("tmessages", e);
                        }
                    }
                });
                showDialog(builder.create());
            } else {
                if (position - 1 < 0 || position - 1 >= wallPapers.size()) {
                    return;
                }
                TLRPC.WallPaper wallPaper = wallPapers.get(position - 1);
                selectedBackground = wallPaper.id;
                listAdapter.notifyDataSetChanged();
                processSelectedBackground();
            }
        }
    });

    processSelectedBackground();

    return fragmentView;
}