Example usage for android.widget TextView TextView

List of usage examples for android.widget TextView TextView

Introduction

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

Prototype

public TextView(Context context) 

Source Link

Usage

From source file:cc.metapro.openct.customviews.TableChooseDialog.java

private void setView() {
    mTableIds = new ArrayList<>(tableMap.size());
    for (String s : tableMap.keySet()) {
        mTableIds.add(s);/*from  www . j a v  a 2  s .c o m*/
    }

    final List<View> views = new ArrayList<>(mTableIds.size());
    for (String s : mTableIds) {
        TextView textView = new TextView(getActivity());

        String content = tableMap.get(s).toString();
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
            textView.setText(Html.fromHtml(content, Html.FROM_HTML_MODE_COMPACT));
        } else {
            textView.setText(Html.fromHtml(content));
        }
        views.add(textView);
    }

    mTabBar.setupWithViewPager(mViewPager);
    mViewPager.setAdapter(new PagerAdapter() {
        @Override
        public int getCount() {
            return mTableIds.size();
        }

        @Override
        public CharSequence getPageTitle(int position) {
            return mTableIds.get(position);
        }

        @Override
        public boolean isViewFromObject(View view, Object object) {
            return view == object;
        }

        @Override
        public void destroyItem(ViewGroup container, int position, Object object) {
            container.removeView(views.get(position));
        }

        @Override
        public Object instantiateItem(ViewGroup container, int position) {
            container.addView(views.get(position));
            return views.get(position);
        }
    });
}

From source file:com.crazy.toutiaonews.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 ww .  j  a v  a  2s  . co  m
 */
protected TextView createDefaultTabView(Context context) {
    TextView textView = new TextView(context);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
    textView.setTypeface(Typeface.DEFAULT_BOLD);

    //  Holo ??
    //  if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB) {
    // If we're running on Honeycomb or newer, then we can use the Theme's
    // selectableItemBackground to ensure that the View has a pressed state
    //       TypedValue outValue = new TypedValue();
    //       getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
    //               outValue, true);
    //       textView.setBackgroundResource(outValue.resourceId);
    //   }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // If we're running on ICS or newer, enable all-caps to match the Action Bar tab style
        textView.setAllCaps(true);
    }

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

    return textView;
}

From source file:com.bryan.example.widget.slidingtablayout.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)}.
 *//*from ww  w . ja v  a2 s  .c om*/
@SuppressLint("NewApi")
protected TextView createDefaultTabView(Context context) {
    /**
     * ?Holo??
     */
    TextView textView = new TextView(context);
    textView.setGravity(Gravity.CENTER);
    textView.setTextSize(TypedValue.COMPLEX_UNIT_SP, TAB_VIEW_TEXT_SIZE_SP);
    // textView.setTypeface(Typeface.DEFAULT_BOLD);//
    textView.setTypeface(Typeface.DEFAULT);

    // if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.HONEYCOMB)
    // {
    // // If we're running on Honeycomb or newer, then we can use the
    // // Theme's
    // // selectableItemBackground to ensure that the View has a pressed
    // // state
    // TypedValue outValue = new TypedValue();
    // getContext().getTheme().resolveAttribute(android.R.attr.selectableItemBackground,
    // outValue, true);
    // textView.setBackgroundResource(outValue.resourceId);
    // }

    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.ICE_CREAM_SANDWICH) {
        // If we're running on ICS or newer, enable all-caps to match the
        // Action Bar tab style
        textView.setAllCaps(true);
    }

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

    return textView;
}

From source file:terse.a1.TerseActivity.java

@Override
public void onCreate(final Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    glSurfaceView = null; // Forget gl on new activity.

    requestWindowFeature(Window.FEATURE_NO_TITLE);
    getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
            WindowManager.LayoutParams.FLAG_FULLSCREEN);

    if (savedInstanceState != null && savedInstanceState.containsKey("TerseActivity")) {
        taSaveMe = savedInstanceState.getString("TerseActivity");
    } else {// www  .  j av a 2 s  . c  o m
        taSaveMe = null;
    }

    Runnable bg = new Runnable() {
        @Override
        public void run() {
            resetTerp();
        }
    };

    Runnable fg = new Runnable() {
        @Override
        public void run() {
            Intent intent = getIntent();
            Uri uri = intent.getData();
            Bundle extras = intent.getExtras();
            String path = uri == null ? "/" : uri.getPath();
            String query = uri == null ? "" : uri.getQuery();

            viewPath(path, query, extras, savedInstanceState);
        }
    };
    if (terp == null) {
        TextView tv = new TextView(TerseActivity.this);
        tv.setText(Static.fmt("Building new TerseTalk VM for world <%s>...", world));
        tv.setTextAppearance(this, R.style.teletype);
        tv.setBackgroundColor(Color.BLACK);
        tv.setTextColor(Color.DKGRAY);
        tv.setTextSize(24);
        setContentView(tv);
        setContentViewThenBgThenFg("ResetSplash", tv, bg, fg);
    } else {
        fg.run();
    }
}

From source file:busradar.madison.StopDialog.java

StopDialog(final Context ctx, final int stopid, final int lat, final int lon) {
    super(ctx);/* www .  jav a 2s  .c o m*/
    this.stopid = stopid;

    // getWindow().requestFeature(Window.FEATURE_LEFT_ICON);
    getWindow().setLayout(LayoutParams.FILL_PARENT, LayoutParams.WRAP_CONTENT);

    final String name = DB.getStopName(stopid);
    setTitle(name);

    routes = get_time_urls(StopDialog.this.stopid);

    // getWindow().setLayout(LayoutParams.FILL_PARENT,
    // LayoutParams.FILL_PARENT);

    setContentView(new RelativeLayout(ctx) {
        {
            addView(new TextView(ctx) {
                {
                    setId(stop_num_id);
                    setText(Html.fromHtml(String.format(
                            "[<a href='http://www.cityofmadison.com/metro/BusStopDepartures/StopID/%04d.pdf'>%04d</a>]",
                            stopid, stopid)));
                    setPadding(0, 0, 5, 0);
                    this.setMovementMethod(LinkMovementMethod.getInstance());
                }
            }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) {
                {
                    addRule(ALIGN_PARENT_RIGHT);
                }
            });

            addView(new ImageView(ctx) {
                boolean enabled;

                @Override
                public void setEnabled(boolean e) {
                    enabled = e;

                    setImageResource(e ? R.drawable.love_enabled : R.drawable.love_disabled);
                    if (e) {
                        G.favorites.add_favorite_stop(stopid, name, lat, lon);
                        Toast.makeText(ctx, "Added stop to Favorites", Toast.LENGTH_SHORT).show();
                    } else {
                        G.favorites.remove_favorite_stop(stopid);
                        Toast.makeText(ctx, "Removed stop from Favorites", Toast.LENGTH_SHORT).show();
                    }
                }

                {
                    enabled = G.favorites.is_stop_favorite(stopid);
                    setImageResource(enabled ? R.drawable.love_enabled : R.drawable.love_disabled);

                    setPadding(0, 0, 10, 0);
                    setOnClickListener(new OnClickListener() {
                        public void onClick(View v) {
                            setEnabled(!enabled);
                        }
                    });
                }
            }, new RelativeLayout.LayoutParams(WRAP_CONTENT, WRAP_CONTENT) {
                {
                    addRule(LEFT_OF, stop_num_id);
                    setMargins(0, -3, 0, 0);
                }
            });

            addView(cur_loading_text = new TextView(ctx) {
                {
                    setText("Loading...");
                    setPadding(5, 0, 0, 0);
                }
            });
            addView(new HorizontalScrollView(ctx) {
                {
                    setId(route_list_id);
                    setHorizontalScrollBarEnabled(false);

                    addView(new LinearLayout(ctx) {
                        float text_size;
                        Button cur_button;
                        {
                            int last_route = -1;
                            for (int i = 0; i < routes.length; i++) {

                                final RouteURL route = routes[i];

                                if (route.route == last_route)
                                    continue;
                                last_route = route.route;

                                addView(new Button(ctx) {
                                    public void setEnabled(boolean e) {
                                        if (e) {
                                            setBackgroundColor(0xff000000 | G.route_points[route.route].color);
                                            setTextSize(TypedValue.COMPLEX_UNIT_PX, text_size * 1.5f);
                                        } else {
                                            setBackgroundColor(0x90000000 | G.route_points[route.route].color);
                                            setTextSize(TypedValue.COMPLEX_UNIT_PX, text_size);
                                        }
                                    }

                                    {
                                        setText(G.route_points[route.route].name);
                                        setTextColor(0xffffffff);
                                        setTypeface(Typeface.DEFAULT_BOLD);
                                        text_size = getTextSize();

                                        if (G.active_route == route.route) {
                                            setEnabled(true);
                                            cur_button = this;
                                        } else
                                            setEnabled(false);

                                        final Button b = this;

                                        setOnClickListener(new OnClickListener() {
                                            public void onClick(View v) {
                                                if (cur_button != null) {
                                                    cur_button.setEnabled(false);
                                                }

                                                if (cur_button == b) {
                                                    cur_button.setEnabled(false);
                                                    cur_button = null;

                                                    selected_route = null;
                                                    update_time_display();
                                                } else {
                                                    cur_button = b;
                                                    cur_button.setEnabled(true);

                                                    selected_route = route;
                                                    update_time_display();
                                                }
                                            }
                                        });

                                    }
                                });
                            }
                        }
                    });
                }
            }, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) {
                {
                    addRule(RelativeLayout.BELOW, stop_num_id);
                    addRule(RelativeLayout.CENTER_HORIZONTAL);
                }
            });

            addView(status_text = new TextView(ctx) {
                {
                    setText("");
                }
            }, new RelativeLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT) {
                {
                    addRule(RelativeLayout.BELOW, route_list_id);
                    addRule(RelativeLayout.CENTER_HORIZONTAL);
                }
            });
            addView(list_view = new ListView(ctx) {
                {
                    setId(time_list_id);
                    setVerticalScrollBarEnabled(false);
                    setAdapter(times_adapter = new BaseAdapter() {

                        public View getView(final int position, View convertView, ViewGroup parent) {
                            CellView v;

                            if (convertView == null)
                                v = new CellView(ctx);
                            else
                                v = (CellView) convertView;

                            RouteTime rt = curr_times.get(position);
                            v.setBackgroundColor(G.route_points[rt.route].color | 0xff000000);
                            v.route_textview.setText(G.route_points[rt.route].name);
                            if (rt.dir != null)
                                v.dir_textview.setText("to " + rt.dir);
                            v.time_textview.setText(rt.time);

                            return v;

                        }

                        public int getCount() {
                            return curr_times.size();
                        }

                        public Object getItem(int position) {
                            return null;
                        }

                        public long getItemId(int position) {
                            return 0;
                        }

                    });
                }
            }, new RelativeLayout.LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT) {
                {
                    addRule(RelativeLayout.BELOW, route_list_id);
                }
            });
        }
    });

    TextView title = (TextView) findViewById(android.R.id.title);
    title.setEllipsize(TextUtils.TruncateAt.MARQUEE);
    title.setSelected(true);
    title.setTextColor(0xffffffff);
    title.setMarqueeRepeatLimit(-1);

    // getWindow().set, value)
    // getWindow().setFeatureDrawableResource(Window.FEATURE_LEFT_ICON,
    // android.R.drawable.ic_dialog_info);

    // title.setGravity(Gravity.CENTER_HORIZONTAL|Gravity.CENTER_VERTICAL);

    if (G.active_route >= 0)
        for (int i = 0; i < routes.length; i++)
            if (routes[i].route == G.active_route) {
                selected_route = routes[i];

                RouteURL[] rnew = new RouteURL[routes.length];
                rnew[0] = selected_route;

                for (int j = 0, k = 1; j < routes.length; j++)
                    if (j != i)
                        rnew[k++] = routes[j];

                routes = rnew;
                break;
            }
    update_time_display();
}

From source file:net.mypapit.mobile.myrepeater.DisplayMap.java

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_display_map);
    overridePendingTransition(R.anim.activity_open_translate, R.anim.activity_close_scale);

    hashMap = new HashMap<Marker, MapInfoObject>();

    if (android.os.Build.VERSION.SDK_INT >= android.os.Build.VERSION_CODES.HONEYCOMB) {
        getActionBar().setDisplayHomeAsUpEnabled(true);
    }/* ww w.j  a v  a2s . com*/

    map = ((SupportMapFragment) getSupportFragmentManager().findFragmentById(R.id.map)).getMap();

    if (map == null) {

        // Log.e("Map NULL", "MAP NULL");
        Toast.makeText(this, "Unable to display Map", Toast.LENGTH_SHORT).show();

    } else {

        LatLng latlng = (LatLng) getIntent().getExtras().get("LatLong");

        Repeater xlocation = new Repeater("", new Double[] { latlng.latitude, latlng.longitude });

        rl = RepeaterListActivity.loadData(R.raw.repeaterdata5, this);
        xlocation.calcDistanceAll(rl);
        rl.sort();

        map.setMyLocationEnabled(true);
        map.setOnInfoWindowClickListener(this);
        map.getUiSettings().setZoomControlsEnabled(true);

        AdView mAdView = (AdView) findViewById(R.id.adViewMap);
        mAdView.loadAd(new AdRequest.Builder().build());

        // counter i, for mapping marker with integer
        int i = 0;

        for (Repeater repeater : rl) {

            MarkerOptions marking = new MarkerOptions();
            marking.position(new LatLng(repeater.getLatitude(), repeater.getLongitude()));
            marking.title(repeater.getCallsign() + " - " + repeater.getDownlink() + "MHz (" + repeater.getClub()
                    + ")");

            marking.snippet("Tone: " + repeater.getTone() + " Shift: " + repeater.getShift());

            RepeaterMapInfo rmi = new RepeaterMapInfo(repeater);
            rmi.setIndex(i);

            hashMap.put(map.addMarker(marking), rmi);

            i++;

        }

        // Marker RKG = map.addMarker(new MarkerOptions().position(new
        // LatLng(6.1,100.3)).title("9M4RKG"));

        map.moveCamera(CameraUpdateFactory.newLatLngZoom(latlng, 10));
        map.animateCamera(CameraUpdateFactory.zoomTo(10), 2000, null);

        cache = this.getSharedPreferences(CACHE_PREFS, 0);

        Date cachedate = new Date(cache.getLong(CACHE_TIME, new Date(20000).getTime()));

        long secs = (new Date().getTime() - cachedate.getTime()) / 1000;
        long hours = secs / 3600L;
        secs = secs % 3600L;
        long mins = secs / 60L;

        if (mins < 5) {
            String jsoncache = cache.getString(CACHE_JSON, "none");
            if (jsoncache.compareToIgnoreCase("none") == 0) {
                new GetUserInfo(latlng, this).execute();

            } else {

                loadfromCache(jsoncache);
                // Toast.makeText(this, "Loaded from cache: " + mins +
                // " mins", Toast.LENGTH_SHORT).show();
            }

        } else {

            new GetUserInfo(latlng, this).execute();

        }

        map.setInfoWindowAdapter(new GoogleMap.InfoWindowAdapter() {

            @Override
            public View getInfoWindow(Marker marker) {
                // TODO Auto-generated method stub
                return null;
            }

            @Override
            public View getInfoContents(Marker marker) {
                Context context = getApplicationContext(); // or
                // getActivity(),
                // YourActivity.this,
                // etc.

                LinearLayout info = new LinearLayout(context);
                info.setOrientation(LinearLayout.VERTICAL);

                TextView title = new TextView(context);
                title.setTextColor(Color.BLACK);
                title.setGravity(Gravity.CENTER);
                title.setTypeface(null, Typeface.BOLD);
                title.setText(marker.getTitle());

                TextView snippet = new TextView(context);
                snippet.setTextColor(Color.GRAY);
                snippet.setText(marker.getSnippet());

                info.addView(title);
                info.addView(snippet);

                return info;
            }
        });

    }

}

From source file:jp.mau.twappremover.MainActivity.java

@Override
public boolean onOptionsItemSelected(MenuItem item) {
    int id = item.getItemId();
    if (id == R.id.action_settings) {
        ScrollView contents = new ScrollView(this);
        LinearLayout layout = new LinearLayout(this);
        layout.setOrientation(LinearLayout.VERTICAL);
        contents.addView(layout);/*from  w  w  w  . j av a  2  s .  co  m*/
        AssetManager asm = getResources().getAssets();
        String[] filelist = null;
        try {
            filelist = asm.list("licenses");
        } catch (Exception ex) {
            ex.printStackTrace();
        }

        if (filelist != null) {
            for (String file : filelist) {
                Gen.debug(file);
                InputStream is = null;
                BufferedReader br = null;
                String txt = "";
                try {
                    is = getAssets().open("licenses/" + file);
                    br = new BufferedReader(new InputStreamReader(is));
                    String str;
                    while ((str = br.readLine()) != null) {
                        txt += str + "\n";
                    }
                } catch (Exception ex) {
                    ex.printStackTrace();
                } finally {
                    try {
                        if (is != null)
                            is.close();
                    } catch (Exception ex) {
                    }
                    try {
                        if (br != null)
                            br.close();
                    } catch (Exception ex) {
                    }
                }
                TextView tv = new TextView(this);
                tv.setText(txt);
                layout.addView(tv);
            }
        }

        // 
        final PopupView dialog = new PopupView(this);
        dialog.setDialog().setLabels(getString(R.string.activity_main_dlgtitle_oss), "")
                .setView(contents, ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT)
                .setCancelable(true)
                .setPositiveBtn(getString(R.string.activity_main_dlgbtn_oss), new OnClickListener() {
                    @Override
                    public void onClick(View v) {
                        dialog.dismiss();
                    }
                }).show();
        return true;
    }
    return super.onOptionsItemSelected(item);
}

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

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

From source file:cn.bingoogol.tabhost.ui.view.PagerSlidingTabStrip.java

private void addTextTab(final int position, String title) {
    TextView tab = new TextView(getContext());
    tab.setText(title);/*w  w w.ja  v  a  2s .  com*/
    tab.setGravity(Gravity.CENTER);
    tab.setSingleLine();
    addTab(position, tab);
}