Example usage for android.widget ImageView setLayoutParams

List of usage examples for android.widget ImageView setLayoutParams

Introduction

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

Prototype

public void setLayoutParams(ViewGroup.LayoutParams params) 

Source Link

Document

Set the layout parameters associated with this view.

Usage

From source file:com.example.khaalijeb.newlistview_module.SlidingTabLayout.java

/**
 * Create a default view to be used for tabs. This is called if a custom tab view is not set via
 * {@link #setCustomTabView(int, int)}./* w  w w.j  av a 2s  . c om*/
 */

protected ImageView createDefaultImageView(Context context) {
    ImageView imageView = new ImageView(context);

    int padding = (int) (TAB_VIEW_PADDING_DIPS * getResources().getDisplayMetrics().density);
    imageView.setPadding(padding, padding, padding, padding);

    //     int width = (int) (getResources().getDisplayMetrics().widthPixels / mViewPager.getAdapter().getCount());
    //    imageView.setMinimumWidth(width);

    imageView.setLayoutParams(
            new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT, 1.0f));

    /*     WindowManager wm = (WindowManager) context.getSystemService(Context.WINDOW_SERVICE);
         Display display = wm.getDefaultDisplay();
         Point size = new Point();
         display.getSize(size);
         imageView.setMaxWidth(size.x /4);
    */

    return imageView;
}

From source file:com.jgkj.bxxc.fragment.IndexFragment2.java

private void scrollView() {
    SharedPreferences sp = getActivity().getSharedPreferences("PicCount", Activity.MODE_PRIVATE);
    final int count = sp.getInt("Count", -1);
    if (count != -1) {
        final ImageView[] dots = new ImageView[count];
        for (int k = 0; k < count; k++) {
            ImageView image = new ImageView(getActivity());
            image.setImageDrawable(getResources().getDrawable(R.drawable.selector));
            image.setId(k);//from   www .  j a  v  a2 s .  c o  m
            wrapParams = new LinearLayout.LayoutParams(ViewPager.LayoutParams.WRAP_CONTENT,
                    ViewPager.LayoutParams.WRAP_CONTENT);
            wrapParams.leftMargin = 5;
            image.setLayoutParams(wrapParams);
            linearlayout.addView(image);
            dots[k] = (ImageView) linearlayout.getChildAt(k);
            dots[k].setEnabled(true);
        }
        final Handler mHandler = new Handler() {
            @Override
            public void handleMessage(Message msg) {
                super.handleMessage(msg);
                if (currentItem < (count - 1)) {
                    currentItem++;
                    viewpager.setCurrentItem(currentItem);
                } else if (currentItem == (count - 1)) {
                    currentItem = 0;
                    viewpager.setCurrentItem(currentItem);
                }
                for (int j = 0; j < count; j++) {
                    dots[j].setEnabled(false);
                }
                dots[currentItem].setEnabled(true);
            }
        };
        TimerTask timerTask = new TimerTask() {
            @Override
            public void run() {
                mHandler.sendEmptyMessage(0);
            }
        };
        timer.schedule(timerTask, 1000, 3000);
    }
}

From source file:com.timothy.android.api.fragment.PageFragmentNew.java

public void setAllComponent(List<HtmlCleanAPI.HtmlContent> hcList) {
    Log.i(LOG_TAG, "setAllComponent()...");
    for (HtmlCleanAPI.HtmlContent hc : hcList) {
        String tag = hc.getTag();
        String content = hc.getContent();
        if (StringUtil.isEmpty(content))
            continue;

        String contentMBlank = StringUtil.mergeBlank(content);
        if (StringUtil.isEmpty(contentMBlank))
            continue;

        String contentRBlank = StringUtil.rmvEnter(StringUtil.trim(contentMBlank));
        if (StringUtil.isEmpty(contentRBlank))
            continue;

        String contentRSpecial = StringUtil.rmvSpecial(contentRBlank);
        if (StringUtil.isEmpty(contentRSpecial))
            continue;

        Log.i(LOG_TAG, "tag:" + tag);
        Log.i(LOG_TAG, "content:" + contentRSpecial);

        if (tag.equalsIgnoreCase("P")) {
            final TextView tagPTV = new TextView(mContext);
            tagPTV.setBackgroundResource(R.drawable.tag_p_drawable);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(2, 3, 2, 3);//from ww w.  j ava2s .co m
            tagPTV.setLayoutParams(lp);
            tagPTV.setPadding(3, 3, 3, 3);
            tagPTV.setPaddingRelative(3, 3, 3, 3);
            tagPTV.setMovementMethod(ScrollingMovementMethod.getInstance());
            tagPTV.setTextColor(Color.BLACK);
            tagPTV.setText(contentRSpecial);
            tagPTV.setTextSize(TEXT_SIZE);
            tagPTV.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    openDialog(tagPTV.getText().toString());
                    return false;
                }
            });
            lineLayout.addView(tagPTV);

        } else if (tag.equalsIgnoreCase("pre")) {
            final TextView tagPre = new TextView(mContext);
            tagPre.setBackgroundColor(Color.parseColor("#D2EADE"));
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(2, 2, 2, 2);
            tagPre.setLayoutParams(lp);
            tagPre.setPadding(2, 2, 2, 2);
            tagPre.setPaddingRelative(2, 2, 2, 2);
            tagPre.setMovementMethod(ScrollingMovementMethod.getInstance());
            tagPre.setTextColor(Color.BLACK);
            //            String contentRSpecial = StringUtil.rmvSpecial(content);
            tagPre.setText(StringUtil.rmvSpecial(content));
            tagPre.setTextSize(TEXT_SIZE);
            tagPre.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    openDialog(tagPre.getText().toString());
                    return false;
                }
            });
            lineLayout.addView(tagPre);
        } else if (tag.equalsIgnoreCase("dt") || tag.equalsIgnoreCase("H1") || tag.equalsIgnoreCase("H2")
                || tag.equalsIgnoreCase("H3")) {//title
            TextView tagDtHTV = new TextView(mContext);
            tagDtHTV.setBackgroundColor(Color.DKGRAY);
            tagDtHTV.setTypeface(null, Typeface.BOLD);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(2, 0, 2, 0);
            tagDtHTV.setLayoutParams(lp);
            tagDtHTV.setPadding(2, 2, 2, 2);
            tagDtHTV.setPaddingRelative(2, 2, 2, 2);
            tagDtHTV.setMovementMethod(ScrollingMovementMethod.getInstance());
            tagDtHTV.setTextColor(Color.WHITE);
            tagDtHTV.setText(contentRSpecial);
            tagDtHTV.setTextSize(TEXT_SIZE);
            lineLayout.addView(tagDtHTV);
        } else if (tag.equalsIgnoreCase("dd")) {
            final TextView tagDD = new TextView(mContext);
            tagDD.setBackgroundResource(R.drawable.tag_p_drawable);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(2, 2, 2, 2);
            tagDD.setLayoutParams(lp);
            tagDD.setPadding(3, 3, 3, 3);
            tagDD.setPaddingRelative(3, 3, 3, 3);
            tagDD.setMovementMethod(ScrollingMovementMethod.getInstance());
            tagDD.setTextColor(Color.BLACK);
            tagDD.setText(contentRSpecial);
            tagDD.setTextSize(TEXT_SIZE);
            tagDD.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    openDialog(tagDD.getText().toString());
                    return false;
                }
            });
            lineLayout.addView(tagDD);
        } else if (tag.equalsIgnoreCase("li")) {
            final TextView tagLigTV = new TextView(mContext);
            tagLigTV.setBackgroundResource(R.drawable.tag_p_drawable);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(2, 2, 2, 2);
            tagLigTV.setLayoutParams(lp);
            tagLigTV.setPaddingRelative(2, 2, 2, 2);
            tagLigTV.setMovementMethod(ScrollingMovementMethod.getInstance());
            tagLigTV.setTextColor(Color.BLACK);
            tagLigTV.setText(contentRSpecial);
            tagLigTV.setTextSize(TEXT_SIZE);
            tagLigTV.setOnLongClickListener(new View.OnLongClickListener() {
                @Override
                public boolean onLongClick(View v) {
                    openDialog(tagLigTV.getText().toString());
                    return false;
                }
            });
            lineLayout.addView(tagLigTV);
        } else if (tag.equalsIgnoreCase("img")) {
            final TextView imgTV = new TextView(mContext);
            imgTV.setBackgroundResource(R.drawable.tag_p_drawable);
            LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            lp.setMargins(2, 2, 2, 2);
            imgTV.setLayoutParams(lp);
            imgTV.setPaddingRelative(2, 2, 2, 2);
            imgTV.setMovementMethod(ScrollingMovementMethod.getInstance());
            imgTV.setTextColor(Color.BLACK);
            imgTV.setText(content);
            imgTV.setTextSize(TEXT_SIZE);
            lineLayout.addView(imgTV);

            ImageView imageView = new ImageView(mContext);
            LinearLayout.LayoutParams imgLP = new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT,
                    LayoutParams.WRAP_CONTENT);
            imageView.setLayoutParams(imgLP);
            Bitmap localBt = getLoacalBitmap(baseFolder + File.separator + content);
            imageView.setImageBitmap(localBt);
            lineLayout.addView(imageView);
        }
    }
}

From source file:org.ayo.robot.anim.transitioneverywhere.ImageTransformSample.java

@Nullable
@Override//from www  . jav a 2  s .co m
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
    View view = inflater.inflate(R.layout.fragment_image_transform, container, false);

    final ViewGroup transitionsContainer = (ViewGroup) view.findViewById(R.id.transitions_container);
    final ImageView imageView = (ImageView) transitionsContainer.findViewById(R.id.image);

    imageView.setOnClickListener(new View.OnClickListener() {

        boolean mExpanded;

        @Override
        public void onClick(View v) {
            mExpanded = !mExpanded;

            TransitionManager.beginDelayedTransition(transitionsContainer, new TransitionSet()
                    .addTransition(new ChangeBounds()).addTransition(new ChangeImageTransform()));

            ViewGroup.LayoutParams params = imageView.getLayoutParams();
            params.height = mExpanded ? ViewGroup.LayoutParams.MATCH_PARENT
                    : ViewGroup.LayoutParams.WRAP_CONTENT;
            imageView.setLayoutParams(params);

            imageView
                    .setScaleType(mExpanded ? ImageView.ScaleType.CENTER_CROP : ImageView.ScaleType.FIT_CENTER);
        }
    });

    return view;
}

From source file:com.brodev.socialapp.view.MarketPlaceDetail.java

private void initView() {

    ImageView userImage = (ImageView) this.findViewById(R.id.image_user);

    if (!"".equals(marketPlace.getUser_image_path())) {
        networkUntil.drawImageUrl(userImage, marketPlace.getUser_image_path(), R.drawable.loading);
    }/*from www.j a v a2  s  .c  o m*/

    userImage.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Intent intent = new Intent(MarketPlaceDetail.this, FriendTabsPager.class);
            intent.putExtra("user_id", marketPlace.getUser_id());
            startActivity(intent);
            return false;
        }
    });

    // set title
    TextView title = (TextView) this.findViewById(R.id.title);
    title.setText(marketPlace.getTitle());
    colorView.changeColorText(title, user.getColor());

    // set content
    TextView content = (TextView) this.findViewById(R.id.content);

    // interesting part starts from here here:
    Html.ImageGetter ig = imageGetter.create(0, marketPlace.getText(), content);

    content.setTag(0);
    content.setText(Html.fromHtml(marketPlace.getText(), ig, null));

    TextView timestampTxt = (TextView) findViewById(R.id.txtTimestamp);
    timestampTxt.setText(phraseManager.getPhrase(getApplicationContext(), "marketplace.posted_on"));
    TextView timestamp = (TextView) findViewById(R.id.time_stamp);
    timestamp.setText(marketPlace.getTime_stamp());
    TextView price = (TextView) this.findViewById(R.id.price);

    if (marketPlace.getPrice() == 0) {
        price.setText(phraseManager.getPhrase(getApplicationContext(), "marketplace.free"));
    } else {
        price.setText(marketPlace.getCurrency() + " " + marketPlace.getPrice());
    }

    TextView locationTxt = (TextView) findViewById(R.id.txtLocation);
    locationTxt.setText(phraseManager.getPhrase(getApplicationContext(), "marketplace.location"));
    TextView txtLocation = (TextView) this.findViewById(R.id.location);
    String location = marketPlace.getCountry_name();

    if (!marketPlace.getCountry_child_name().equals("")) {
        location += " > " + marketPlace.getCountry_child_name();
    }
    if (!marketPlace.getCity_name().equals("")) {
        location += " > " + marketPlace.getCity_name();
    }

    txtLocation.setText(location);
    // set short text
    TextView fullnameTxt = (TextView) findViewById(R.id.txtFullname);
    fullnameTxt.setText(phraseManager.getPhrase(getApplicationContext(), "marketplace.posted_by"));

    TextView shortText = (TextView) findViewById(R.id.fullName);
    shortText.setText(marketPlace.getFull_name());
    colorView.changeColorText(shortText, user.getColor());

    shortText.setOnTouchListener(new View.OnTouchListener() {

        @Override
        public boolean onTouch(View v, MotionEvent event) {
            Intent intent = new Intent(MarketPlaceDetail.this, FriendTabsPager.class);
            intent.putExtra("user_id", marketPlace.getUser_id());
            startActivity(intent);
            return false;
        }
    });

    TextView total_like = (TextView) findViewById(R.id.total_like);
    total_like.setText(String.valueOf(marketPlace.getTotal_like()));
    colorView.changeColorText(total_like, user.getColor());

    TextView total_comment = (TextView) findViewById(R.id.total_comment);
    total_comment.setText(String.valueOf(marketPlace.getTotal_comment()));
    colorView.changeColorText(total_comment, user.getColor());

    ImageView likeImg = (ImageView) this.findViewById(R.id.likes_feed_txt);
    ImageView commentImg = (ImageView) this.findViewById(R.id.comments_feed_txt);
    colorView.changeColorLikeCommnent(likeImg, commentImg, user.getColor());

    //get list images
    if (!marketPlace.getImages().equals("")) {
        LinearLayout listImages = (LinearLayout) findViewById(R.id.listImages);
        JSONObject objOutputImage = null;
        try {
            JSONArray objImages = new JSONArray(marketPlace.getImages());
            for (int i = 0; i < objImages.length(); i++) {
                objOutputImage = objImages.getJSONObject(i);
                ImageView imageView = new ImageView(getApplicationContext());

                LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(
                        (int) getResources().getDimension(R.dimen.marketplace_image),
                        (int) getResources().getDimension(R.dimen.marketplace_image));

                lp.setMargins(5, 5, 5, 0);

                imageView.setLayoutParams(lp);

                imageView.setScaleType(ImageView.ScaleType.CENTER_CROP);
                final String imagePath = objOutputImage.getString("image_path");
                networkUntil.drawImageUrl(imageView, imagePath, R.drawable.loading);

                imageView.setOnClickListener(new View.OnClickListener() {

                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getApplicationContext(), ImageActivity.class);
                        intent.putExtra("image", imagePath);
                        intent.putExtra("title", marketPlace.getTitle());
                        startActivity(intent);
                    }
                });

                listImages.addView(imageView);

            }

        } catch (JSONException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
    } else {
        this.findViewById(R.id.horizontalScrollView1).setVisibility(View.GONE);
        this.findViewById(R.id.marketplace_list_image_view).setVisibility(View.GONE);
    }

}

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

@SuppressWarnings("unchecked")
@Override//from   ww  w .  j  ava  2 s . 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:self.philbrown.droidQuery.Example.ExampleActivity.java

/**
 * Refreshes the list of cells containing App.net messages. This <em>ListView</em> is actually
 * a <em>scrollable LinearLayout</em>, and is assembled in much the same way a layout would be
 * made using <em>JavaScript</em>, with the <em>CSS3</em> attribute <em>overscroll-y: scroll</em>.
 * <br>//from w w  w.  ja v  a2s  .  co  m
 * For this example, the public stream is retrieved using <em>ajax</em>, and for each message
 * received, a new cell is created. For each cell, a new <em>ajax</em> request is started to
 * retrieve the thumbnail image for the user. As all these events occur on a background thread, the
 * main ScrollView is populated with cells and displayed to the user.
 * <br>
 * The stream <em>JSON</em> request is performed in a <em>global ajax</em> request, which will
 * trigger the global start and stop events (which show a progress indicator, using a droidQuery
 * extension). The image get requests are not global, so they will not trigger global events.
 */
public void refresh() {
    $.ajax(new AjaxOptions().url("https://alpha-api.app.net/stream/0/posts/stream/global").dataType("json")
            .type("GET").error(new Function() {
                @Override
                public void invoke($ droidQuery, Object... params) {
                    //Object error, int status, String reason
                    Object error = params[0];
                    int status = (Integer) params[1];
                    String reason = (String) params[2];
                    Log.w("app.net Client", "Could not complete request: " + reason);
                }
            }).success(new Function() {
                @Override
                public void invoke($ droidQuery, Object... params) {
                    //Object, reason
                    JSONObject json = (JSONObject) params[0];
                    String reason = (String) params[1];
                    try {
                        Map<String, ?> map = $.map(json);
                        JSONArray datas = (JSONArray) map.get("data");

                        if (datas.length() != 0) {
                            //clear old subviews in layout
                            $.with(ExampleActivity.this, R.id.example_layout).selectChildren().remove();

                            //get each message infos and create a cell
                            for (int i = 0; i < datas.length(); i++) {
                                JSONObject jdata = (JSONObject) datas.get(i);
                                Map<String, ?> data = $.map(jdata);

                                String text = data.get("text").toString();

                                Map<String, ?> user = $.map((JSONObject) data.get("user"));

                                String username = user.get("username").toString();
                                String avatarURL = ((JSONObject) user.get("avatar_image")).getString("url");

                                //get Avatar image in a new task (but go ahead and create the cell for now)
                                LinearLayout cell = new LinearLayout(ExampleActivity.this);
                                LinearLayout.LayoutParams cell_params = new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.MATCH_PARENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                cell_params.bottomMargin = 5;
                                cell.setLayoutParams(cell_params);
                                cell.setOrientation(LinearLayout.HORIZONTAL);
                                cell.setWeightSum(8);
                                cell.setPadding(5, 5, 5, 5);
                                cell.setBackgroundColor(Color.parseColor("#333333"));
                                final LinearLayout fcell = cell;

                                //contains the image location
                                ImageView image = new ImageView(ExampleActivity.this);
                                image.setId(99);
                                LinearLayout.LayoutParams ip_params = new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                ip_params.weight = 2;
                                image.setLayoutParams(ip_params);
                                image.setPadding(0, 0, 5, 0);
                                $.with(image).attr("alpha", 0.0f);
                                cell.addView(image);
                                final ImageView fimage = image;

                                //the text location in the cell
                                LinearLayout body = new LinearLayout(ExampleActivity.this);
                                LinearLayout.LayoutParams body_params = new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                body_params.weight = 5;
                                body.setLayoutParams(body_params);
                                body.setOrientation(LinearLayout.VERTICAL);
                                body.setGravity(Gravity.CENTER_VERTICAL);
                                cell.addView(body);

                                //the username
                                TextView name = new TextView(ExampleActivity.this);
                                LinearLayout.LayoutParams name_params = new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.WRAP_CONTENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                name.setLayoutParams(name_params);
                                name.setTextColor(Color.GRAY);
                                name.setText(username);
                                body.addView(name);

                                //the message
                                TextView message = new TextView(ExampleActivity.this);
                                LinearLayout.LayoutParams msg_params = new LinearLayout.LayoutParams(
                                        LinearLayout.LayoutParams.WRAP_CONTENT,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                message.setLayoutParams(msg_params);
                                message.setTextColor(Color.WHITE);
                                message.setTextSize(18);
                                message.setText(text);
                                body.addView(message);

                                CheckBox checkbox = new CheckBox(ExampleActivity.this);
                                LinearLayout.LayoutParams box_params = new LinearLayout.LayoutParams(0,
                                        LinearLayout.LayoutParams.WRAP_CONTENT);
                                box_params.weight = 1;
                                checkbox.setLayoutParams(box_params);

                                cell.addView(checkbox);

                                $.with(ExampleActivity.this, R.id.example_layout).add(cell);
                                //$.with(fimage).image(avatarURL, 200, 200, $.noop());
                                $.ajax(new AjaxOptions(avatarURL).type("GET").dataType("image").imageHeight(200)
                                        .imageWidth(200).global(false).success(new Function() {
                                            @Override
                                            public void invoke($ droidQuery, Object... params) {
                                                //Object, reason
                                                Bitmap src = (Bitmap) params[0];
                                                String reason = (String) params[1];
                                                $.with(fimage).val(src);
                                                try {
                                                    $.with(fimage)
                                                            .fadeIn(new AnimationOptions("{ duration: 400 }"));
                                                } catch (Throwable e) {
                                                    e.printStackTrace();
                                                }
                                                LinearLayout.LayoutParams lparams = (LinearLayout.LayoutParams) fcell
                                                        .getLayoutParams();
                                                try {
                                                    lparams.height = Math.min(src.getWidth(),
                                                            fimage.getWidth());
                                                } catch (Throwable t) {
                                                    //ignore NPE
                                                }

                                                fcell.setLayoutParams(lparams);
                                            }
                                        }).error(new Function() {
                                            @Override
                                            public void invoke($ droidQuery, Object... params) {
                                                //Object error, int status, String reason
                                                Object error = params[0];
                                                int status = (Integer) params[1];
                                                String reason = (String) params[2];
                                                Log.w("app.net Client",
                                                        "Could not complete image request: " + reason);
                                            }
                                        }));

                            }
                        } else {
                            Log.w("app.net client", "could not update data");
                        }
                    } catch (Throwable t) {
                        t.printStackTrace();
                    }
                }
            }));
}

From source file:ca.cmput301f13t03.adventure_datetime.view.FragmentView.java

public void setUpView() {
    if (_fragment == null)
        return;/*w w w  .  j av  a2s . c  om*/

    /** Layout items **/
    _filmLayout = (LinearLayout) _rootView.findViewById(R.id.filmstrip);
    _filmstrip = (HorizontalScrollView) _rootView.findViewById(R.id.filmstrip_wrapper);
    _choices = (Button) _rootView.findViewById(R.id.choices);
    _content = (TextView) _rootView.findViewById(R.id.content);

    if (_fragment.getStoryMedia() == null)
        _fragment.setStoryMedia(new ArrayList<Image>());

    /* Run on UI Thread for server stuff */
    getActivity().runOnUiThread(new Runnable() {
        @Override
        public void run() {

            /** Programmatically set filmstrip height **/
            if (_fragment.getStoryMedia().size() > 0)
                _filmstrip.getLayoutParams().height = FILM_STRIP_SIZE;
            else
                _filmstrip.getLayoutParams().height = 0;

            _content.setText(_fragment.getStoryText());
            _filmLayout.removeAllViews();

            // 1) Create new ImageView and add to the LinearLayout
            // 2) Set appropriate Layout Params to ImageView
            // 3) Give onClickListener for going to fullscreen
            LinearLayout.LayoutParams lp;
            //for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {
            for (int i = 0; i < _fragment.getStoryMedia().size(); i++) {

                ImageView li = new ImageView(getActivity());
                li.setScaleType(ScaleType.CENTER_INSIDE);
                li.setImageBitmap(_fragment.getStoryMedia().get(i).decodeBitmap());
                _filmLayout.addView(li);

                lp = (LinearLayout.LayoutParams) li.getLayoutParams();
                lp.setMargins(10, 10, 10, 10);
                lp.width = FILM_STRIP_SIZE;
                lp.height = FILM_STRIP_SIZE;
                lp.gravity = Gravity.CENTER_VERTICAL;
                li.setLayoutParams(lp);

                li.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        Intent intent = new Intent(getActivity(), FullScreen_Image.class);
                        intent.putExtra(FullScreen_Image.TAG_AUTHOR, false);
                        startActivity(intent);
                    }
                });
            }

            if (_fragment.getChoices().size() > 0) {
                /** Choices **/
                final List<String> choices = new ArrayList<String>();
                for (Choice choice : _fragment.getChoices())
                    choices.add(choice.getText());
                choices.add("I'm feeling lucky.");

                _choices.setText("Actions");
                _choices.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(v.getContext()).setTitle("Actions").setCancelable(true)
                                .setItems(choices.toArray(new String[choices.size()]),
                                        new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int which) {

                                                /** You feeling lucky, punk? **/
                                                if (which == _fragment.getChoices().size())
                                                    which = (int) (Math.random()
                                                            * _fragment.getChoices().size());

                                                Choice choice = _fragment.getChoices().get(which);

                                                Toast.makeText(FragmentView.this.getActivity(),
                                                        choice.getText(), Toast.LENGTH_LONG).show();
                                                Locator.getUserController().MakeChoice(choice);
                                            }
                                        })
                                .create().show();
                    }
                });
            } else {
                /** End of story **/
                Locator.getUserController().deleteBookmark();
                _choices.setText("The End");
                _choices.setOnClickListener(new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        new AlertDialog.Builder(v.getContext()).setTitle("La Fin").setCancelable(true)
                                .setPositiveButton("Play Again", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        Locator.getUserController().StartStory(_fragment.getStoryID());
                                    }
                                })
                                .setNegativeButton("Change Adventures", new DialogInterface.OnClickListener() {
                                    @Override
                                    public void onClick(DialogInterface dialog, int which) {
                                        if (!_isEditing)
                                            getActivity().onBackPressed();
                                    }
                                }).create().show();

                    }
                });
            }
        }
    });

}

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

@Override
public void handle(final Activity activity, final CancellableTask task, final Callback callback) {
    try {//from   www .j  a v a2s  .c  om
        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:com.ibm.mil.readyapps.physio.fragments.PainLocationFragment.java

/**
 * Moves the current marker on the bodyLayout to the given location.
 *
 * @param x x location to move the marker.
 * @param y y location to move the marker.
 *///from w  ww  .  ja va2  s.  c o  m
private void movePointer(int x, int y) {

    y -= getYOffset();

    //Log.d("MOVE_POINTER", "Moving pointer to: " + x + ", " + y);

    ImageView pointer = pointers.elementAt(pointers.size() - 1);
    pointer.setLayoutParams(setLayoutParams(x, y));

    bodyLayout.invalidate();

}