List of usage examples for android.widget LinearLayout setWeightSum
@android.view.RemotableViewMethod public void setWeightSum(float weightSum)
From source file:com.matthewmitchell.wakeifyplus.MinutesSecondsFragment.java
@Override public Dialog onCreateDialog(Bundle savedInstanceState) { TableRow.LayoutParams twoLP = new TableRow.LayoutParams(0, 0, 0.2f); TableRow.LayoutParams threeLP = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT, TableRow.LayoutParams.WRAP_CONTENT, 0.3f); View spacer = new View(activity); spacer.setLayoutParams(twoLP);//w w w . j av a2s . c om spacer.setVisibility(View.INVISIBLE); final NumberPicker minutes = new NumberPicker(activity); minutes.setMaxValue(30); minutes.setMinValue(0); minutes.setValue(defaultMinute); minutes.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); LinearLayout minutesLayout = new LinearLayout(activity); minutesLayout.addView(minutes); minutesLayout.setGravity(Gravity.CENTER); minutesLayout.setLayoutParams(threeLP); final NumberPicker seconds = new NumberPicker(activity); seconds.setMaxValue(59); seconds.setMinValue(0); seconds.setValue(defaultSecond); seconds.setDescendantFocusability(NumberPicker.FOCUS_BLOCK_DESCENDANTS); LinearLayout secondsLayout = new LinearLayout(activity); secondsLayout.addView(seconds); secondsLayout.setGravity(Gravity.CENTER); secondsLayout.setLayoutParams(threeLP); LinearLayout layout = new LinearLayout(activity); layout.addView(spacer); layout.addView(minutesLayout); layout.addView(secondsLayout); layout.setWeightSum(1.0f); AlertDialog.Builder builder = new AlertDialog.Builder(getActivity()); builder.setMessage("Set Volume Ramping Time").setView(layout) .setPositiveButton("Set", new DialogInterface.OnClickListener() { @Override public void onClick(DialogInterface dialog, int which) { activity.rampingMinutes = minutes.getValue(); activity.rampingSeconds = seconds.getValue(); TextView edit = (TextView) activity.findViewById(R.id.volume_ramping); edit.setText(activity.rampingMinutes + "m" + activity.rampingSeconds + "s"); } }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() { public void onClick(DialogInterface dialog, int id) { // Do nothing. } }); // Create the AlertDialog object and return it return builder.create(); }
From source file:com.gandulf.guilib.view.adapter.MultiFragmentPagerAdapter.java
@Override public Object instantiateItem(View container, int position) { if (mCurTransaction == null) { mCurTransaction = mFragmentManager.beginTransaction(); }/*from w w w. j a v a 2s .c o m*/ LinearLayout v = new LinearLayout(mContext); v.setOrientation(LinearLayout.HORIZONTAL); v.setWeightSum(getCount(position)); int startIndex = getStartIndex(position); int containerId = 0; final int size = getCount(position); for (int i = 0; i < size; i++) { containerId = startIndex + i; String name = makeFragmentName(container.getId(), containerId); Fragment fragment = mFragmentManager.findFragmentByTag(name); FrameLayout fragmentView = new FrameLayout(mContext); LayoutParams layoutParams = new LayoutParams(0, LayoutParams.MATCH_PARENT, 1); fragmentView.setLayoutParams(layoutParams); fragmentView.setId(containerId); v.addView(fragmentView, i); if (fragment != null) { Debug.verbose("Attaching item #" + position + ": f=" + fragment + " id:" + containerId); mCurTransaction.attach(fragment); } else { // index is 1 based remove 1 to get a 0-based fragment = getItem(position, i); if (fragment != null) { Debug.verbose("Adding item #" + position + ": f=" + fragment + " id:" + containerId); mCurTransaction.add(containerId, fragment, name); } } if (fragment != null && !mCurrentPrimaryItems.contains(fragment)) { fragment.setMenuVisibility(false); fragment.setUserVisibleHint(false); } } mCurTransaction.setTransition(FragmentTransaction.TRANSIT_FRAGMENT_FADE); ((ViewPager) container).addView(v, 0); return v; }
From source file:org.telegram.ui.Cells.SessionCell.java
public SessionCell(Context context) { super(context); if (paint == null) { paint = new Paint(); paint.setColor(ContextCompat.getColor(context, R.color.divider)); paint.setStrokeWidth(1);/*from w w w . ja va 2 s . c o m*/ } setElevation(AndroidUtilities.dp(2)); setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.HORIZONTAL); linearLayout.setWeightSum(1); addView(linearLayout, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, 30, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 17, 11, 11, 0)); nameTextView = new TextView(context); nameTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); nameTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); nameTextView.setLines(1); nameTextView.setTypeface(AndroidUtilities.getTypeface("fonts/rmedium.ttf")); nameTextView.setMaxLines(1); nameTextView.setSingleLine(true); nameTextView.setEllipsize(TextUtils.TruncateAt.END); nameTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); onlineTextView = new TextView(context); onlineTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); onlineTextView.setGravity((LocaleController.isRTL ? Gravity.LEFT : Gravity.RIGHT) | Gravity.TOP); if (LocaleController.isRTL) { linearLayout.addView(onlineTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.LEFT | Gravity.TOP, 0, 2, 0, 0)); linearLayout.addView(nameTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, Gravity.RIGHT | Gravity.TOP, 10, 0, 0, 0)); } else { linearLayout.addView(nameTextView, LayoutHelper.createLinear(0, LayoutHelper.MATCH_PARENT, 1.0f, Gravity.LEFT | Gravity.TOP, 0, 0, 10, 0)); linearLayout.addView(onlineTextView, LayoutHelper.createLinear(LayoutHelper.WRAP_CONTENT, LayoutHelper.MATCH_PARENT, Gravity.RIGHT | Gravity.TOP, 0, 2, 0, 0)); } detailTextView = new TextView(context); detailTextView.setTextColor(ContextCompat.getColor(context, R.color.primary_text)); detailTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); detailTextView.setLines(1); detailTextView.setMaxLines(1); detailTextView.setSingleLine(true); detailTextView.setEllipsize(TextUtils.TruncateAt.END); detailTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); addView(detailTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 17, 36, 17, 0)); detailExTextView = new TextView(context); detailExTextView.setTextColor(ContextCompat.getColor(context, R.color.secondary_text) /*0xff999999*/); detailExTextView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 14); detailExTextView.setLines(1); detailExTextView.setMaxLines(1); detailExTextView.setSingleLine(true); detailExTextView.setEllipsize(TextUtils.TruncateAt.END); detailExTextView.setGravity((LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP); addView(detailExTextView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.WRAP_CONTENT, (LocaleController.isRTL ? Gravity.RIGHT : Gravity.LEFT) | Gravity.TOP, 17, 59, 17, 0)); }
From source file:org.telegram.ui.IdenticonActivity.java
@Override public View createView(Context context) { actionBar.setBackButtonImage(R.drawable.ic_ab_back); actionBar.setAllowOverlayTitle(true); actionBar.setTitle(LocaleController.getString("EncryptionKey", R.string.EncryptionKey)); actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() { @Override/* ww w .jav a 2 s. c o m*/ public void onItemClick(int id) { if (id == -1) { finishFragment(); } } }); fragmentView = new LinearLayout(context); LinearLayout linearLayout = (LinearLayout) fragmentView; linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setWeightSum(100); linearLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.card_background)); fragmentView.setOnTouchListener(new View.OnTouchListener() { @Override public boolean onTouch(View v, MotionEvent event) { return true; } }); FrameLayout frameLayout = new FrameLayout(context); frameLayout.setPadding(AndroidUtilities.dp(20), AndroidUtilities.dp(20), AndroidUtilities.dp(20), AndroidUtilities.dp(20)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 50.0f)); ImageView identiconView = new ImageView(context); identiconView.setScaleType(ImageView.ScaleType.FIT_XY); frameLayout.addView(identiconView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); frameLayout = new FrameLayout(context); frameLayout.setBackgroundColor(ContextCompat.getColor(context, R.color.background)); frameLayout.setPadding(AndroidUtilities.dp(10), 0, AndroidUtilities.dp(10), AndroidUtilities.dp(10)); linearLayout.addView(frameLayout, LayoutHelper.createLinear(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT, 50.0f)); TextView textView = new TextView(context); textView.setTextColor(ContextCompat.getColor(context, R.color.secondary_text)); textView.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16); textView.setLinksClickable(true); textView.setClickable(true); textView.setMovementMethod(new LinkMovementMethodMy()); //textView.setAutoLinkMask(Linkify.WEB_URLS); textView.setLinkTextColor(Theme.MSG_LINK_TEXT_COLOR); textView.setGravity(Gravity.CENTER); frameLayout.addView(textView, LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT)); TLRPC.EncryptedChat encryptedChat = MessagesController.getInstance().getEncryptedChat(chat_id); if (encryptedChat != null) { IdenticonDrawable drawable = new IdenticonDrawable(); identiconView.setImageDrawable(drawable); drawable.setEncryptedChat(encryptedChat); TLRPC.User user = MessagesController.getInstance().getUser(encryptedChat.user_id); SpannableStringBuilder hash = new SpannableStringBuilder(); if (encryptedChat.key_hash.length > 16) { String hex = Utilities.bytesToHex(encryptedChat.key_hash); for (int a = 0; a < 32; a++) { if (a != 0) { if (a % 8 == 0) { hash.append('\n'); } else if (a % 4 == 0) { hash.append(' '); } } hash.append(hex.substring(a * 2, a * 2 + 2)); hash.append(' '); } hash.append("\n\n"); } hash.append(AndroidUtilities.replaceTags(LocaleController.formatString("EncryptionKeyDescription", R.string.EncryptionKeyDescription, user.first_name, user.first_name))); final String url = "telegram.org"; int index = hash.toString().indexOf(url); if (index != -1) { hash.setSpan( new URLSpanReplacement( LocaleController.getString("EncryptionKeyLink", R.string.EncryptionKeyLink)), index, index + url.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE); } textView.setText(hash); } return fragmentView; }
From source file:com.astuetz.PagerSlidingTabStripPlus.java
/** * Add new text view to the linear layout that contains the tab title* * @param position of the linear layout in the tabsContainer * @param text is the text of the subtitle *///from www . ja v a2 s. c o m public void addSubtitleAtTab(int position, String text) { LinearLayout tab = getSingleTabLayoutAtPosition(position); tab.setWeightSum(tab.getChildCount() + 1); if (tab.getChildCount() == 1) { tab.getChildAt(0).setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 1)); } ((TextView) tab.getChildAt(0)).setGravity(Gravity.CENTER_HORIZONTAL); TextView newSubTab = new TextView(getContext()); newSubTab.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, 0, 1)); newSubTab.setText(text); newSubTab.setGravity(Gravity.CENTER_HORIZONTAL); tab.addView(newSubTab); updateTabStyles(); }
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. j a v a 2 s . c o 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:com.vonglasow.michael.satstat.ui.RadioSectionFragment.java
private final void addWifiResult(ScanResult result) { // needed to pass a persistent reference to the OnClickListener final ScanResult r = result; android.view.View.OnClickListener clis = new android.view.View.OnClickListener() { @Override//from w w w . ja v a 2 s . c o m public void onClick(View v) { onWifiEntryClick(r.BSSID); } }; LinearLayout wifiLayout = new LinearLayout(wifiAps.getContext()); wifiLayout.setLayoutParams( new LinearLayout.LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT)); wifiLayout.setOrientation(LinearLayout.HORIZONTAL); wifiLayout.setWeightSum(22); wifiLayout.setMeasureWithLargestChildEnabled(false); ImageView wifiType = new ImageView(wifiAps.getContext()); wifiType.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.MATCH_PARENT, 3)); if (WifiCapabilities.isAdhoc(result)) { wifiType.setImageResource(R.drawable.ic_content_wifi_adhoc); } else if ((WifiCapabilities.isEnterprise(result)) || (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.EAP)) { wifiType.setImageResource(R.drawable.ic_content_wifi_eap); } else if (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.PSK) { wifiType.setImageResource(R.drawable.ic_content_wifi_psk); } else if (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.WEP) { wifiType.setImageResource(R.drawable.ic_content_wifi_wep); } else if (WifiCapabilities.getScanResultSecurity(result) == WifiCapabilities.OPEN) { wifiType.setImageResource(R.drawable.ic_content_wifi_open); } else { wifiType.setImageResource(R.drawable.ic_content_wifi_unknown); } wifiType.setScaleType(ScaleType.CENTER); wifiLayout.addView(wifiType); TableLayout wifiDetails = new TableLayout(wifiAps.getContext()); wifiDetails.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 19)); TableRow innerRow1 = new TableRow(wifiAps.getContext()); TextView newMac = new TextView(wifiAps.getContext()); newMac.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 14)); newMac.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Medium); newMac.setText(result.BSSID); innerRow1.addView(newMac); TextView newCh = new TextView(wifiAps.getContext()); newCh.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 2)); newCh.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Medium); newCh.setText(getChannelFromFrequency(result.frequency)); innerRow1.addView(newCh); TextView newLevel = new TextView(wifiAps.getContext()); newLevel.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 3)); newLevel.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Medium); newLevel.setText(String.valueOf(result.level)); innerRow1.addView(newLevel); innerRow1.setOnClickListener(clis); wifiDetails.addView(innerRow1, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); TableRow innerRow2 = new TableRow(wifiAps.getContext()); TextView newSSID = new TextView(wifiAps.getContext()); newSSID.setLayoutParams(new TableRow.LayoutParams(0, LayoutParams.WRAP_CONTENT, 19)); newSSID.setTextAppearance(wifiAps.getContext(), android.R.style.TextAppearance_Small); newSSID.setText(result.SSID); innerRow2.addView(newSSID); innerRow2.setOnClickListener(clis); wifiDetails.addView(innerRow2, new TableLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT)); wifiLayout.addView(wifiDetails); wifiLayout.setOnClickListener(clis); wifiAps.addView(wifiLayout); }
From source file:ru.adios.budgeter.widgets.DataTableLayout.java
private LinearLayout getCenteredRowText(Context context, String text, float layoutWeightSum, boolean largeText, float textViewWeight) { final LinearLayout inner = new LinearLayout(context); final TableRow.LayoutParams innerParams = new TableRow.LayoutParams(TableRow.LayoutParams.MATCH_PARENT, TableRow.LayoutParams.WRAP_CONTENT, 1f); innerParams.span = itemsPerInnerRow; inner.setLayoutParams(innerParams);//from w w w .j ava2s . com inner.setWeightSum(layoutWeightSum); inner.setBackgroundResource(R.drawable.cell_shape); final TextView nameTextView = new TextView(context); nameTextView.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT, textViewWeight)); nameTextView.setTextAppearance(context, largeText ? android.R.style.TextAppearance_Large : android.R.style.TextAppearance_Medium); nameTextView.setText(text); nameTextView.setGravity(Gravity.CENTER); inner.addView(nameTextView); return inner; }
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 w w w .j av a 2 s.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()); } }); } } }