List of usage examples for android.widget LinearLayout VERTICAL
int VERTICAL
To view the source code for android.widget LinearLayout VERTICAL.
Click Source Link
From source file:org.getlantern.firetweet.activity.support.SignInActivity.java
@Override public void onActivityResult(final int requestCode, final int resultCode, final Intent data) { switch (requestCode) { case REQUEST_EDIT_API: { if (resultCode == RESULT_OK) { mAPIUrlFormat = data.getStringExtra(Accounts.API_URL_FORMAT); mAuthType = data.getIntExtra(Accounts.AUTH_TYPE, Accounts.AUTH_TYPE_OAUTH); mSameOAuthSigningUrl = data.getBooleanExtra(Accounts.SAME_OAUTH_SIGNING_URL, false); mNoVersionSuffix = data.getBooleanExtra(Accounts.NO_VERSION_SUFFIX, false); mConsumerKey = data.getStringExtra(Accounts.CONSUMER_KEY); mConsumerSecret = data.getStringExtra(Accounts.CONSUMER_SECRET); final boolean isTwipOMode = mAuthType == Accounts.AUTH_TYPE_TWIP_O_MODE; mSigninSignupContainer/*from w w w. ja v a2 s . c o m*/ .setOrientation(isTwipOMode ? LinearLayout.VERTICAL : LinearLayout.HORIZONTAL); } setSignInButton(); invalidateOptionsMenu(); break; } case REQUEST_BROWSER_SIGN_IN: { if (resultCode == BaseActionBarActivity.RESULT_OK && data != null) { doLogin(data); } break; } } super.onActivityResult(requestCode, resultCode, data); }
From source file:fr.cph.chicago.core.adapter.NearbyAdapter.java
private View handleTrains(final int position, View convertView, @NonNull final ViewGroup parent) { // Train//w w w .j a va2 s. c o m final Station station = stations.get(position); final Set<TrainLine> trainLines = station.getLines(); TrainViewHolder viewHolder; if (convertView == null || convertView.getTag() == null) { final LayoutInflater vi = (LayoutInflater) parent.getContext() .getSystemService(Context.LAYOUT_INFLATER_SERVICE); convertView = vi.inflate(R.layout.list_nearby, parent, false); viewHolder = new TrainViewHolder(); viewHolder.resultLayout = (LinearLayout) convertView.findViewById(R.id.nearby_results); viewHolder.stationNameView = (TextView) convertView.findViewById(R.id.station_name); viewHolder.imageView = (ImageView) convertView.findViewById(R.id.icon); viewHolder.details = new HashMap<>(); viewHolder.arrivalTime = new HashMap<>(); convertView.setTag(viewHolder); } else { viewHolder = (TrainViewHolder) convertView.getTag(); } viewHolder.stationNameView.setText(station.getName()); viewHolder.imageView .setImageDrawable(ContextCompat.getDrawable(parent.getContext(), R.drawable.ic_train_white_24dp)); for (final TrainLine trainLine : trainLines) { if (trainArrivals.indexOfKey(station.getId()) != -1) { final List<Eta> etas = trainArrivals.get(station.getId()).getEtas(trainLine); if (etas.size() != 0) { final LinearLayout llv; boolean cleanBeforeAdd = false; if (viewHolder.details.containsKey(trainLine)) { llv = viewHolder.details.get(trainLine); cleanBeforeAdd = true; } else { final LinearLayout llh = new LinearLayout(context); llh.setOrientation(LinearLayout.HORIZONTAL); llh.setPadding(line1PaddingColor, stopsPaddingTop, 0, 0); llv = new LinearLayout(context); llv.setOrientation(LinearLayout.VERTICAL); llv.setPadding(line1PaddingColor, 0, 0, 0); llh.addView(llv); viewHolder.resultLayout.addView(llh); viewHolder.details.put(trainLine, llv); } final List<String> keysCleaned = new ArrayList<>(); for (final Eta eta : etas) { final Stop stop = eta.getStop(); final String key = station.getName() + "_" + trainLine.toString() + "_" + stop.getDirection().toString() + "_" + eta.getDestName(); if (viewHolder.arrivalTime.containsKey(key)) { final RelativeLayout insideLayout = viewHolder.arrivalTime.get(key); final TextView timing = (TextView) insideLayout.getChildAt(2); if (cleanBeforeAdd && !keysCleaned.contains(key)) { timing.setText(""); keysCleaned.add(key); } final String timingText = timing.getText() + eta.getTimeLeftDueDelay() + " "; timing.setText(timingText); } else { final LinearLayout.LayoutParams leftParam = new LinearLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); final RelativeLayout insideLayout = new RelativeLayout(context); insideLayout.setLayoutParams(leftParam); final RelativeLayout lineIndication = LayoutUtil.createColoredRoundForFavorites(context, trainLine); int lineId = Util.generateViewId(); lineIndication.setId(lineId); final RelativeLayout.LayoutParams availableParam = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); availableParam.addRule(RelativeLayout.RIGHT_OF, lineId); availableParam.setMargins(Util.convertDpToPixel(context, 10), 0, 0, 0); final TextView stopName = new TextView(context); final String destName = eta.getDestName() + ": "; stopName.setText(destName); stopName.setTextColor(ContextCompat.getColor(parent.getContext(), R.color.grey_5)); stopName.setLayoutParams(availableParam); int availableId = Util.generateViewId(); stopName.setId(availableId); final RelativeLayout.LayoutParams availableValueParam = new RelativeLayout.LayoutParams( ViewGroup.LayoutParams.WRAP_CONTENT, ViewGroup.LayoutParams.WRAP_CONTENT); availableValueParam.addRule(RelativeLayout.RIGHT_OF, availableId); availableValueParam.setMargins(0, 0, 0, 0); final TextView timing = new TextView(context); final String timeLeftDueDelay = eta.getTimeLeftDueDelay() + " "; timing.setText(timeLeftDueDelay); timing.setTextColor(ContextCompat.getColor(parent.getContext(), R.color.grey)); timing.setLines(1); timing.setEllipsize(TruncateAt.END); timing.setLayoutParams(availableValueParam); insideLayout.addView(lineIndication); insideLayout.addView(stopName); insideLayout.addView(timing); llv.addView(insideLayout); viewHolder.arrivalTime.put(key, insideLayout); } } } } } convertView.setOnClickListener(new NearbyOnClickListener(googleMap, markers, station.getId(), station.getStopsPosition().get(0).getLatitude(), station.getStopsPosition().get(0).getLongitude())); return convertView; }
From source file:com.mishiranu.dashchan.ui.navigator.DrawerForm.java
public DrawerForm(Context context, Context unstyledContext, Callback callback, WatcherService.Client watcherServiceClient) { this.context = context; this.unstyledContext = unstyledContext; this.callback = callback; this.watcherServiceClient = watcherServiceClient; float density = ResourceUtils.obtainDensity(context); LinearLayout linearLayout = new LinearLayout(context); linearLayout.setOrientation(LinearLayout.VERTICAL); linearLayout.setLayoutParams(new SortableListView.LayoutParams(SortableListView.LayoutParams.MATCH_PARENT, SortableListView.LayoutParams.WRAP_CONTENT)); LinearLayout editTextContainer = new LinearLayout(context); editTextContainer.setGravity(Gravity.CENTER_VERTICAL); linearLayout.addView(editTextContainer); searchEdit = new SafePasteEditText(context); searchEdit.setOnKeyListener((v, keyCode, event) -> { if (event.getAction() == KeyEvent.ACTION_UP && keyCode == KeyEvent.KEYCODE_BACK) { v.clearFocus();/* www . j a v a2 s . c o m*/ } return false; }); searchEdit.setHint(context.getString(R.string.text_code_number_address)); searchEdit.setOnEditorActionListener(this); searchEdit.setInputType(InputType.TYPE_CLASS_TEXT | InputType.TYPE_TEXT_VARIATION_URI); searchEdit.setImeOptions(EditorInfo.IME_ACTION_GO | EditorInfo.IME_FLAG_NO_EXTRACT_UI); ImageView searchIcon = new ImageView(context, null, android.R.attr.buttonBarButtonStyle); searchIcon.setImageResource(ResourceUtils.getResourceId(context, R.attr.buttonForward, 0)); searchIcon.setScaleType(ImageView.ScaleType.CENTER); searchIcon.setOnClickListener(this); editTextContainer.addView(searchEdit, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1)); editTextContainer.addView(searchIcon, (int) (40f * density), (int) (40f * density)); if (C.API_LOLLIPOP) { editTextContainer.setPadding((int) (12f * density), (int) (8f * density), (int) (8f * density), 0); } else { editTextContainer.setPadding(0, (int) (2f * density), (int) (4f * density), (int) (2f * density)); } LinearLayout selectorContainer = new LinearLayout(context); selectorContainer.setBackgroundResource( ResourceUtils.getResourceId(context, android.R.attr.selectableItemBackground, 0)); selectorContainer.setOrientation(LinearLayout.HORIZONTAL); selectorContainer.setGravity(Gravity.CENTER_VERTICAL); selectorContainer.setOnClickListener(v -> { hideKeyboard(); setChanSelectMode(!chanSelectMode); }); linearLayout.addView(selectorContainer); selectorContainer.setMinimumHeight((int) (40f * density)); if (C.API_LOLLIPOP) { selectorContainer.setPadding((int) (16f * density), 0, (int) (16f * density), 0); ((LinearLayout.LayoutParams) selectorContainer.getLayoutParams()).topMargin = (int) (4f * density); } else { selectorContainer.setPadding((int) (8f * density), 0, (int) (12f * density), 0); } chanNameView = new TextView(context, null, android.R.attr.textAppearanceListItem); chanNameView.setTextSize(TypedValue.COMPLEX_UNIT_SP, C.API_LOLLIPOP ? 14f : 16f); if (C.API_LOLLIPOP) { chanNameView.setTypeface(GraphicsUtils.TYPEFACE_MEDIUM); } else { chanNameView.setFilters(new InputFilter[] { new InputFilter.AllCaps() }); } selectorContainer.addView(chanNameView, new LinearLayout.LayoutParams(0, LinearLayout.LayoutParams.WRAP_CONTENT, 1)); chanSelectorIcon = new ImageView(context); chanSelectorIcon.setImageResource(ResourceUtils.getResourceId(context, R.attr.buttonDropDownDrawer, 0)); selectorContainer.addView(chanSelectorIcon, (int) (24f * density), (int) (24f * density)); ((LinearLayout.LayoutParams) chanSelectorIcon.getLayoutParams()).gravity = Gravity.CENTER_VERTICAL | Gravity.END; headerView = linearLayout; inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE); chans.add(new ListItem(ListItem.ITEM_DIVIDER, 0, 0, null)); int color = ResourceUtils.getColor(context, R.attr.drawerIconColor); ChanManager manager = ChanManager.getInstance(); Collection<String> availableChans = manager.getAvailableChanNames(); for (String chanName : availableChans) { ChanConfiguration configuration = ChanConfiguration.get(chanName); if (configuration.getOption(ChanConfiguration.OPTION_READ_POSTS_COUNT)) { watcherSupportSet.add(chanName); } Drawable drawable = manager.getIcon(chanName, color); chanIcons.put(chanName, drawable); chans.add( new ListItem(ListItem.ITEM_CHAN, chanName, null, null, configuration.getTitle(), 0, drawable)); } if (availableChans.size() == 1) { selectorContainer.setVisibility(View.GONE); } }
From source file:de.gebatzens.sia.fragment.RemoteDataFragment.java
/** * * @return horizontal screen orientation *///from w w w . j av a2 s .co m public boolean createRootLayout(LinearLayout l) { l.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); l.setOrientation(LinearLayout.VERTICAL); if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_LANDSCAPE) { l.setPadding(toPixels(55), toPixels(4), toPixels(55), toPixels(4)); return true; } else if (getResources().getConfiguration().orientation == Configuration.ORIENTATION_PORTRAIT) { l.setPadding(toPixels(4), toPixels(4), toPixels(4), toPixels(4)); } return false; }
From source file:com.superrecycleview.superlibrary.utils.SuperDivider.java
@Override public void onDrawOver(Canvas canvas, RecyclerView parent, RecyclerView.State state) { if (parent.getLayoutManager() == null || parent.getAdapter() == null) { return;/*from ww w. j a va2 s.c o m*/ } int itemCount = parent.getAdapter().getItemCount(); if (mOrientation == LinearLayout.VERTICAL) { drawVertical(canvas, parent, itemCount); } else { drawVertical(canvas, parent, itemCount); } }
From source file:com.achep.header2actionbar.HeaderFragmentSupportV4.java
@Override public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) { final Activity activity = getActivity(); assert activity != null; mFrameLayout = new FrameLayout(activity); mHeader = onCreateHeaderView(inflater, mFrameLayout); mHeaderHeader = mHeader.findViewById(android.R.id.title); mHeaderBackground = mHeader.findViewById(android.R.id.background); assert mHeader.getLayoutParams() != null; mHeader.measure(View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED), View.MeasureSpec.makeMeasureSpec(0, View.MeasureSpec.UNSPECIFIED)); mHeaderHeight = mHeader.getMeasuredHeight(); mFakeHeader = new Space(activity); View content = onCreateContentView(inflater, mFrameLayout); mContentView = content;//from w w w .j a va2 s . co m Log.i(TAG, "container:" + container.getMeasuredHeight() + ",mHeaderHeight=" + mHeaderHeight); final View topContentView = container; if (content instanceof ListView) { isListViewEmpty = true; final ListView listView = (ListView) content; mFakeHeader.setLayoutParams(new ListView.LayoutParams(0, mHeaderHeight)); listView.addHeaderView(mFakeHeader); listView.setOnScrollListener(new AbsListView.OnScrollListener() { @Override public void onScrollStateChanged(AbsListView absListView, int scrollState) { if (mOnScrollListener != null) { mOnScrollListener.onScrollStateChanged(absListView, scrollState); } } @Override public void onScroll(AbsListView absListView, int firstVisibleItem, int visibleItemCount, int totalItemCount) { if (isListViewEmpty) { scrollHeaderTo(0); } else { final View child = absListView.getChildAt(0); assert child != null; scrollHeaderTo(child == mFakeHeader ? child.getTop() : -mHeaderHeight); } } }); } else { topContentView.getViewTreeObserver() .addOnGlobalLayoutListener(new ViewTreeObserver.OnGlobalLayoutListener() { @SuppressWarnings("deprecation") @Override public void onGlobalLayout() { //Remove it here unless you want to get this callback for EVERY //layout pass, which can get you into infinite loops if you ever //modify the layout from within this method. topContentView.getViewTreeObserver().removeGlobalOnLayoutListener(this); //Now you can get the width and height from content int actionBarHeight = 0; TypedValue tv = new TypedValue(); if (getActivity().getTheme().resolveAttribute(android.R.attr.actionBarSize, tv, true)) { actionBarHeight = TypedValue.complexToDimensionPixelSize(tv.data, getResources().getDisplayMetrics()); } Log.i(TAG, "topContentView:" + topContentView.getHeight() + ", actionBarHeight:" + actionBarHeight + ", getStatusBarHeight:" + getStatusBarHeight()); ViewGroup.LayoutParams lp = mContentView.getLayoutParams(); lp.height = topContentView.getHeight() - actionBarHeight - getStatusBarHeight(); mContentView.setLayoutParams(lp); } }); // Merge fake header view and content view. final LinearLayout view = new LinearLayout(activity); view.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); view.setOrientation(LinearLayout.VERTICAL); mFakeHeader.setLayoutParams(new LinearLayout.LayoutParams(0, mHeaderHeight)); view.addView(mFakeHeader); view.addView(content); // Put merged content to ScrollView final NotifyingScrollView scrollView = new NotifyingScrollView(activity); scrollView.addView(view); scrollView.setVerticalScrollBarEnabled(false); scrollView.setOverScrollMode(ScrollView.OVER_SCROLL_NEVER); scrollView.setOnScrollChangedListener(new NotifyingScrollView.OnScrollChangedListener() { @Override public void onScrollChanged(ScrollView who, int l, int t, int oldl, int oldt) { Log.i(TAG, "onScrollChanged scroll ot -t :" + (-t)); scrollHeaderTo(-t); } }); mContentWrapper = scrollView; content = scrollView; } mFrameLayout.addView(content); mFrameLayout.addView(mHeader); // Content overlay view always shows at the top of content. if ((mContentOverlay = onCreateContentOverlayView(inflater, mFrameLayout)) != null) { mFrameLayout.addView(mContentOverlay, new FrameLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT)); } // Post initial scroll mFrameLayout.post(new Runnable() { @Override public void run() { Log.i(TAG, "post initial scroll to 0"); // SEAN: walk around for scroll position bug if (mContentWrapper != null) { mContentWrapper.scrollTo(0, 0); } scrollHeaderTo(0, true); } }); return mFrameLayout; }
From source file:com.poinsart.votar.VotarMain.java
private void adjustLayoutForOrientation(int orientation) { if (orientation == Configuration.ORIENTATION_LANDSCAPE) { mainLayout.setOrientation(LinearLayout.HORIZONTAL); controlLayout/*from w w w . java 2s. co m*/ .setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1)); } else if (orientation == Configuration.ORIENTATION_PORTRAIT) { mainLayout.setOrientation(LinearLayout.VERTICAL); controlLayout .setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.MATCH_PARENT, 1)); } }
From source file:org.odk.collect.android.widgets.ExStringWidget.java
public ExStringWidget(Context context, FormEntryPrompt prompt) { super(context, prompt); TableLayout.LayoutParams params = new TableLayout.LayoutParams(); params.setMargins(7, 5, 7, 5);/*from w w w .ja va 2 s. c o m*/ // set text formatting answer = new EditText(context); answer.setId(ViewIds.generateViewId()); answer.setTextSize(TypedValue.COMPLEX_UNIT_DIP, answerFontsize); answer.setLayoutParams(params); textBackground = answer.getBackground(); answer.setBackground(null); answer.setTextColor(ContextCompat.getColor(context, R.color.primaryTextColor)); // capitalize nothing answer.setKeyListener(new TextKeyListener(Capitalize.NONE, false)); // needed to make long read only text scroll answer.setHorizontallyScrolling(false); answer.setSingleLine(false); String s = prompt.getAnswerText(); if (s != null) { answer.setText(s); } if (formEntryPrompt.isReadOnly() || hasExApp) { answer.setFocusable(false); answer.setEnabled(false); } String exSpec = prompt.getAppearanceHint().replaceFirst("^ex[:]", ""); final String intentName = ExternalAppsUtils.extractIntentName(exSpec); final Map<String, String> exParams = ExternalAppsUtils.extractParameters(exSpec); final String buttonText; final String errorString; String v = formEntryPrompt.getSpecialFormQuestionText("buttonText"); buttonText = (v != null) ? v : context.getString(R.string.launch_app); v = formEntryPrompt.getSpecialFormQuestionText("noAppErrorString"); errorString = (v != null) ? v : context.getString(R.string.no_app); launchIntentButton = getSimpleButton(buttonText); launchIntentButton.setEnabled(!formEntryPrompt.isReadOnly()); launchIntentButton.setOnClickListener(new View.OnClickListener() { @Override public void onClick(View v) { Intent i = new Intent(intentName); if (isActivityAvailable(i)) { try { ExternalAppsUtils.populateParameters(i, exParams, formEntryPrompt.getIndex().getReference()); FormController formController = Collect.getInstance().getFormController(); if (formController == null) { return; } formController.setIndexWaitingForData(formEntryPrompt.getIndex()); fireActivity(i); } catch (ExternalParamsException e) { Timber.e(e); onException(e.getMessage()); } } else { onException(errorString); } } private void onException(String toastText) { hasExApp = false; if (!formEntryPrompt.isReadOnly()) { answer.setBackground(textBackground); answer.setFocusable(true); answer.setFocusableInTouchMode(true); answer.setEnabled(true); } launchIntentButton.setEnabled(false); launchIntentButton.setFocusable(false); cancelWaitingForBinaryData(); Toast.makeText(getContext(), toastText, Toast.LENGTH_SHORT).show(); ExStringWidget.this.answer.requestFocus(); Timber.e(toastText); } }); // finish complex layout LinearLayout answerLayout = new LinearLayout(getContext()); answerLayout.setOrientation(LinearLayout.VERTICAL); answerLayout.addView(launchIntentButton); answerLayout.addView(answer); addAnswerView(answerLayout); }
From source file:com.nttec.everychan.http.recaptcha.Recaptcha2fallback.java
@Override public void handle(final Activity activity, final CancellableTask task, final Callback callback) { try {/* www. j av a 2 s . co 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()); } }); } } }