Example usage for android.widget TextView setMovementMethod

List of usage examples for android.widget TextView setMovementMethod

Introduction

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

Prototype

public final void setMovementMethod(MovementMethod movement) 

Source Link

Document

Sets the android.text.method.MovementMethod for handling arrow key movement for this TextView.

Usage

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

public void showAlertDialog(String title, String message, View view, String positiveText,
        final Runnable positive, String negativeText, final Runnable negative, boolean link,
        boolean notCancelable) {
    AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);
    builder.setCancelable(!notCancelable);

    if (title != null) {
        builder.setTitle(title);//from  w  w  w. jav  a2  s  . c  o  m
    }
    if (message != null) {
        builder.setMessage(message);
    } else if (view != null) {
        builder.setView(view);
    }

    if (positive != null) {
        if (positiveText == null) {
            positiveText = getString(android.R.string.ok);
        }

        builder.setPositiveButton(positiveText, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (positive != null) {
                    positive.run();
                }
            }
        });
    }

    if (negative != null) {
        if (negativeText == null) {
            negativeText = getString(android.R.string.cancel);
        }

        builder.setNegativeButton(negativeText, new OnClickListener() {
            @Override
            public void onClick(DialogInterface dialog, int which) {
                if (negative != null) {
                    negative.run();
                }
            }
        });
    }

    AlertDialog d = builder.create();

    d.show();

    if (link) {
        TextView test = (TextView) d.findViewById(android.R.id.message);

        if (test != null) {
            test.setMovementMethod(LinkMovementMethod.getInstance());
        }
    }
}

From source file:org.tvbrowser.tvbrowser.TvBrowser.java

private void showEpgDonateInfo() {
    if (!SHOWING_DONATION_INFO && hasEpgDonateChannelsSubscribed()) {
        final SharedPreferences pref = PreferenceManager.getDefaultSharedPreferences(TvBrowser.this);

        final String year = String.valueOf(Calendar.getInstance().get(Calendar.YEAR));
        int month = Calendar.getInstance().get(Calendar.MONTH);

        final long now = System.currentTimeMillis();
        long firstDownload = pref.getLong(getString(R.string.EPG_DONATE_FIRST_DATA_DOWNLOAD), now);
        long lastDownload = pref.getLong(getString(R.string.EPG_DONATE_LAST_DATA_DOWNLOAD), now);
        long lastShown = pref.getLong(getString(R.string.EPG_DONATE_LAST_DONATION_INFO_SHOWN),
                (now - (60 * 24 * 60 * 60000L)));

        Calendar monthTest = Calendar.getInstance();
        monthTest.setTimeInMillis(lastShown);
        int shownMonth = monthTest.get(Calendar.MONTH);

        boolean firstTimeoutReached = (firstDownload + (14 * 24 * 60 * 60000L)) < now;
        boolean lastTimoutReached = lastDownload > (now - ((42 * 24 * 60 * 60000L)));
        boolean alreadyShowTimeoutReached = (lastShown + (14 * 24 * 60 * 60000L) < now);
        boolean alreadyShownThisMonth = shownMonth == month;
        boolean dontShowAgainThisYear = year
                .equals(pref.getString(getString(R.string.EPG_DONATE_DONT_SHOW_AGAIN_YEAR), "0"));
        boolean radomShow = Math.random() > 0.33;

        boolean show = firstTimeoutReached && lastTimoutReached && alreadyShowTimeoutReached
                && !alreadyShownThisMonth && !dontShowAgainThisYear && radomShow;

        //Log.d("info21", "firstTimeoutReached (" + ((now - firstDownload)/(24 * 60 * 60000L)) + "): " + firstTimeoutReached + " lastTimoutReached: " + lastTimoutReached + " alreadyShowTimeoutReached: " + alreadyShowTimeoutReached + " alreadyShownThisMonth: " + alreadyShownThisMonth + " dontShowAgainThisYear: " + dontShowAgainThisYear + " randomShow: " + radomShow + " SHOW: " + show);

        if (show) {
            AlertDialog.Builder builder = new AlertDialog.Builder(TvBrowser.this);

            String info = getString(R.string.epg_donate_info);
            String amount = getString(R.string.epg_donate_amount);
            String percentInfo = getString(R.string.epg_donate_percent_info);

            String amountValue = pref.getString(
                    getString(R.string.EPG_DONATE_CURRENT_DONATION_AMOUNT_PREFIX) + "_" + year,
                    getString(R.string.epg_donate_current_donation_amount_default));
            int percentValue = Integer
                    .parseInt(pref.getString(getString(R.string.EPG_DONATE_CURRENT_DONATION_PERCENT), "-1"));

            amount = amount.replace("{0}", year).replace("{1}", amountValue);

            info = info.replace("{0}", "<h2>" + amount + "</h2>");

            builder.setTitle(R.string.epg_donate_name);
            builder.setCancelable(false);

            View view = getLayoutInflater().inflate(R.layout.dialog_epg_donate_info, getParentViewGroup(),
                    false);/*from w w w  . j av  a 2  s  . c  o  m*/

            TextView message = (TextView) view.findViewById(R.id.dialog_epg_donate_message);
            message.setText(Html.fromHtml(info));
            message.setMovementMethod(LinkMovementMethod.getInstance());

            TextView percentInfoView = (TextView) view.findViewById(R.id.dialog_epg_donate_percent_info);
            percentInfoView.setText(Html.fromHtml(percentInfo, null, new NewsTagHandler()));

            SeekBar percent = (SeekBar) view.findViewById(R.id.dialog_epg_donate_percent);
            percent.setEnabled(false);

            if (percentValue >= 0) {
                percent.setProgress(percentValue);
            } else {
                percentInfoView.setVisibility(View.GONE);
                percent.setVisibility(View.GONE);
            }

            final Spinner reason = (Spinner) view.findViewById(R.id.dialog_epg_donate_reason_selection);
            reason.setEnabled(false);

            final CheckBox dontShowAgain = (CheckBox) view.findViewById(R.id.dialog_epg_donate_dont_show_again);
            dontShowAgain.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
                @Override
                public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
                    reason.setEnabled(isChecked);
                }
            });

            builder.setView(view);
            builder.setPositiveButton(android.R.string.ok, new DialogInterface.OnClickListener() {
                @Override
                public void onClick(DialogInterface dialog, int which) {
                    SHOWING_DONATION_INFO = false;
                    Editor edit = pref.edit();
                    edit.putLong(getString(R.string.EPG_DONATE_LAST_DONATION_INFO_SHOWN), now);

                    if (dontShowAgain.isChecked()) {
                        edit.putString(getString(R.string.EPG_DONATE_DONT_SHOW_AGAIN_YEAR), year);
                    }

                    edit.commit();
                }
            });

            builder.show();
            SHOWING_DONATION_INFO = true;
        }
    }
}

From source file:org.schabi.newpipe.VideoItemDetailFragment.java

private void updateInfo(final StreamInfo info) {
    try {/* w w w  .j a  v a2  s. c  o m*/
        Context c = getContext();
        VideoInfoItemViewCreator videoItemViewCreator = new VideoInfoItemViewCreator(
                LayoutInflater.from(getActivity()));

        RelativeLayout textContentLayout = (RelativeLayout) activity.findViewById(R.id.detailTextContentLayout);
        final TextView videoTitleView = (TextView) activity.findViewById(R.id.detailVideoTitleView);
        TextView uploaderView = (TextView) activity.findViewById(R.id.detailUploaderView);
        TextView viewCountView = (TextView) activity.findViewById(R.id.detailViewCountView);
        TextView thumbsUpView = (TextView) activity.findViewById(R.id.detailThumbsUpCountView);
        TextView thumbsDownView = (TextView) activity.findViewById(R.id.detailThumbsDownCountView);
        TextView uploadDateView = (TextView) activity.findViewById(R.id.detailUploadDateView);
        TextView descriptionView = (TextView) activity.findViewById(R.id.detailDescriptionView);
        FrameLayout nextVideoFrame = (FrameLayout) activity.findViewById(R.id.detailNextVideoFrame);
        RelativeLayout nextVideoRootFrame = (RelativeLayout) activity
                .findViewById(R.id.detailNextVideoRootLayout);
        Button nextVideoButton = (Button) activity.findViewById(R.id.detailNextVideoButton);
        TextView similarTitle = (TextView) activity.findViewById(R.id.detailSimilarTitle);
        Button backgroundButton = (Button) activity
                .findViewById(R.id.detailVideoThumbnailWindowBackgroundButton);
        View topView = activity.findViewById(R.id.detailTopView);
        View nextVideoView = null;
        if (info.next_video != null) {
            nextVideoView = videoItemViewCreator.getViewFromVideoInfoItem(null, nextVideoFrame,
                    info.next_video);
        } else {
            activity.findViewById(R.id.detailNextVidButtonAndContentLayout).setVisibility(View.GONE);
            activity.findViewById(R.id.detailNextVideoTitle).setVisibility(View.GONE);
            activity.findViewById(R.id.detailNextVideoButton).setVisibility(View.GONE);
        }

        progressBar.setVisibility(View.GONE);
        if (nextVideoView != null) {
            nextVideoFrame.addView(nextVideoView);
        }

        initThumbnailViews(info, nextVideoFrame);

        textContentLayout.setVisibility(View.VISIBLE);
        if (android.os.Build.VERSION.SDK_INT < 18) {
            playVideoButton.setVisibility(View.VISIBLE);
        } else {
            ImageView playArrowView = (ImageView) activity.findViewById(R.id.playArrowView);
            playArrowView.setVisibility(View.VISIBLE);
        }

        if (!showNextVideoItem) {
            nextVideoRootFrame.setVisibility(View.GONE);
            similarTitle.setVisibility(View.GONE);
        }

        videoTitleView.setText(info.title);

        topView.setOnTouchListener(new View.OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                if (event.getAction() == android.view.MotionEvent.ACTION_UP) {
                    ImageView arrow = (ImageView) activity.findViewById(R.id.toggleDescriptionView);
                    View extra = activity.findViewById(R.id.detailExtraView);
                    if (extra.getVisibility() == View.VISIBLE) {
                        extra.setVisibility(View.GONE);
                        arrow.setImageResource(R.drawable.arrow_down);
                    } else {
                        extra.setVisibility(View.VISIBLE);
                        arrow.setImageResource(R.drawable.arrow_up);
                    }
                }
                return true;
            }
        });

        // Since newpipe is designed to work even if certain information is not available,
        // the UI has to react on missing information.
        videoTitleView.setText(info.title);
        if (!info.uploader.isEmpty()) {
            uploaderView.setText(info.uploader);
        } else {
            activity.findViewById(R.id.detailUploaderWrapView).setVisibility(View.GONE);
        }
        if (info.view_count >= 0) {
            viewCountView.setText(Localization.localizeViewCount(info.view_count, c));
        } else {
            viewCountView.setVisibility(View.GONE);
        }
        if (info.dislike_count >= 0) {
            thumbsDownView.setText(Localization.localizeNumber(info.dislike_count, c));
        } else {
            thumbsDownView.setVisibility(View.INVISIBLE);
            activity.findViewById(R.id.detailThumbsDownImgView).setVisibility(View.GONE);
        }
        if (info.like_count >= 0) {
            thumbsUpView.setText(Localization.localizeNumber(info.like_count, c));
        } else {
            thumbsUpView.setVisibility(View.GONE);
            activity.findViewById(R.id.detailThumbsUpImgView).setVisibility(View.GONE);
            thumbsDownView.setVisibility(View.GONE);
            activity.findViewById(R.id.detailThumbsDownImgView).setVisibility(View.GONE);
        }
        if (!info.upload_date.isEmpty()) {
            uploadDateView.setText(Localization.localizeDate(info.upload_date, c));
        } else {
            uploadDateView.setVisibility(View.GONE);
        }
        if (!info.description.isEmpty()) {
            descriptionView.setText(Html.fromHtml(info.description));
        } else {
            descriptionView.setVisibility(View.GONE);
        }

        descriptionView.setMovementMethod(LinkMovementMethod.getInstance());

        // parse streams
        Vector<VideoStream> streamsToUse = new Vector<>();
        for (VideoStream i : info.video_streams) {
            if (useStream(i, streamsToUse)) {
                streamsToUse.add(i);
            }
        }

        nextVideoButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent detailIntent = new Intent(getActivity(), VideoItemDetailActivity.class);
                /*detailIntent.putExtra(
                        VideoItemDetailFragment.ARG_ITEM_ID, currentVideoInfo.nextVideo.id); */
                detailIntent.putExtra(VideoItemDetailFragment.VIDEO_URL, info.next_video.webpage_url);
                detailIntent.putExtra(VideoItemDetailFragment.STREAMING_SERVICE, streamingServiceId);
                startActivity(detailIntent);
            }
        });
        textContentLayout.setVisibility(View.VISIBLE);

        if (info.related_videos != null && !info.related_videos.isEmpty()) {
            initSimilarVideos(info, videoItemViewCreator);
        } else {
            activity.findViewById(R.id.detailSimilarTitle).setVisibility(View.GONE);
            activity.findViewById(R.id.similarVideosView).setVisibility(View.GONE);
        }

        setupActionBarHandler(info);

        if (autoPlayEnabled) {
            playVideo(info);
        }

        if (android.os.Build.VERSION.SDK_INT < 18) {
            playVideoButton.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    playVideo(info);
                }
            });
        }

        backgroundButton.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                playVideo(info);
            }
        });

    } catch (java.lang.NullPointerException e) {
        Log.w(TAG, "updateInfo(): Fragment closed before thread ended work... or else");
        e.printStackTrace();
    }
}

From source file:github.popeen.dsub.fragments.SelectDirectoryFragment.java

private void setupTextDisplay(final View header) {

    final TextView titleView = (TextView) header.findViewById(R.id.select_album_title);
    if (playlistName != null) {
        titleView.setText(playlistName);
    } else if (podcastName != null) {
        Collections.reverse(entries);
        titleView.setText(podcastName);/* ww  w. j a  va2 s  . c om*/
        titleView.setPadding(0, 6, 4, 8);
    } else if (name != null) {
        titleView.setText(name);
        if (artistInfo != null) {
            titleView.setPadding(0, 6, 4, 8);
        }
    } else if (share != null) {
        titleView.setVisibility(View.GONE);
    }

    int songCount = 0;

    Set<String> artists = new HashSet<String>();
    Set<Integer> years = new HashSet<Integer>();
    totalDuration = 0;
    for (Entry entry : entries) {
        if (!entry.isDirectory()) {
            songCount++;
            if (entry.getArtist() != null) {
                artists.add(entry.getArtist());
            }
            if (entry.getYear() != null) {
                years.add(entry.getYear());
            }
            Integer duration = entry.getDuration();
            if (duration != null) {
                totalDuration += duration;
            }
        }
    }
    String artistName = "";
    bookDescription = "Could not collect any info about the book at this time";
    try {

        artistName = artists.iterator().next();
        String endpoint = "getBookDirectory";
        if (Util.isTagBrowsing(context)) {
            endpoint = "getBook";
        }
        SharedPreferences prefs = Util.getPreferences(context);
        String url = Util.getRestUrl(context, endpoint) + "&id=" + directory.getId() + "&f=json";

        Log.w("GetInfo", url);
        String artist, title;
        int year = 0;
        artist = title = "";

        try {
            artist = artists.iterator().next();
        } catch (Exception e) {
            Log.w("GetInfoArtist", e.toString());
        }
        try {
            title = titleView.getText().toString();
        } catch (Exception e) {
            Log.w("GetInfoTitle", e.toString());
        }
        try {
            year = years.iterator().next();
        } catch (Exception e) {
            Log.w("GetInfoYear", e.toString());
        }

        BookInfoAPIParams params = new BookInfoAPIParams(url, artist, title, year);
        bookInfo = new BookInfoAPI(context).execute(params).get();
        bookDescription = bookInfo[0];
        bookReader = bookInfo[1];

    } catch (Exception e) {
        Log.w("GetInfoError", e.toString());
    }
    if (bookDescription.equals("noInfo")) {
        bookDescription = "The server has no description for this book";
    }

    final TextView artistView = (TextView) header.findViewById(R.id.select_album_artist);
    if (podcastDescription != null || artistInfo != null || bookDescription != null) {
        artistView.setVisibility(View.VISIBLE);

        String text = "";
        if (bookDescription != null) {
            text = bookDescription;
        }
        if (podcastDescription != null) {
            text = podcastDescription;
        }
        if (artistInfo != null) {
            text = artistInfo.getBiography();
        }
        Spanned spanned = null;
        if (text != null) {
            String newText = "";
            try {
                if (!artistName.equals("")) {
                    newText += "<b>" + context.getResources().getString(R.string.main_artist) + "</b>: "
                            + artistName + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                if (totalDuration > 0) {
                    newText += "<b>" + context.getResources().getString(R.string.album_book_reader) + "</b>: "
                            + bookReader + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                if (totalDuration > 0) {
                    newText += "<b>" + context.getResources().getString(R.string.album_book_length) + "</b>: "
                            + Util.formatDuration(totalDuration) + "<br/>";
                }
            } catch (Exception e) {
            }
            try {
                newText += text + "<br/>";
            } catch (Exception e) {
            }
            spanned = Html.fromHtml(newText);
        }

        artistView.setText(spanned);
        artistView.setSingleLine(false);
        final int minLines = context.getResources().getInteger(R.integer.TextDescriptionLength);
        artistView.setLines(minLines);
        artistView.setTextAppearance(context, android.R.style.TextAppearance_Small);

        final Spanned spannedText = spanned;
        artistView.setOnClickListener(new View.OnClickListener() {
            @TargetApi(Build.VERSION_CODES.JELLY_BEAN)
            @Override
            public void onClick(View v) {
                if (artistView.getMaxLines() == minLines) {
                    // Use LeadingMarginSpan2 to try to make text flow around image
                    Display display = context.getWindowManager().getDefaultDisplay();
                    ImageView coverArtView = (ImageView) header.findViewById(R.id.select_album_art);
                    coverArtView.measure(display.getWidth(), display.getHeight());

                    int height, width;
                    ViewGroup.MarginLayoutParams vlp = (ViewGroup.MarginLayoutParams) coverArtView
                            .getLayoutParams();
                    if (coverArtView.getDrawable() != null) {
                        height = coverArtView.getMeasuredHeight() + coverArtView.getPaddingBottom();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    } else {
                        height = coverArtView.getHeight();
                        width = coverArtView.getWidth() + coverArtView.getPaddingRight();
                    }
                    float textLineHeight = artistView.getPaint().getTextSize();

                    int lines = (int) Math.ceil(height / textLineHeight) + 1;

                    SpannableString ss = new SpannableString(spannedText);
                    ss.setSpan(new MyLeadingMarginSpan2(lines, width), 0, ss.length(),
                            Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                    View linearLayout = header.findViewById(R.id.select_album_text_layout);
                    RelativeLayout.LayoutParams params = (RelativeLayout.LayoutParams) linearLayout
                            .getLayoutParams();
                    int[] rules = params.getRules();
                    rules[RelativeLayout.RIGHT_OF] = 0;
                    params.leftMargin = vlp.rightMargin;

                    artistView.setText(ss);
                    artistView.setMaxLines(100);

                    vlp = (ViewGroup.MarginLayoutParams) titleView.getLayoutParams();
                    vlp.leftMargin = width;
                } else {
                    artistView.setMaxLines(minLines);
                }
            }
        });
        artistView.setMovementMethod(LinkMovementMethod.getInstance());
    } else if (topTracks) {
        artistView.setText(R.string.menu_top_tracks);
        artistView.setVisibility(View.VISIBLE);
    } else if (showAll) {
        artistView.setText(R.string.menu_show_all);
        artistView.setVisibility(View.VISIBLE);
    } else if (artists.size() == 1) {
        String artistText = artists.iterator().next();
        if (years.size() == 1) {
            artistText += " - " + years.iterator().next();
        }
        artistView.setText(artistText);
        artistView.setVisibility(View.VISIBLE);
    } else {
        artistView.setVisibility(View.GONE);
    }

    TextView songCountView = (TextView) header.findViewById(R.id.select_album_song_count);
    TextView songLengthView = (TextView) header.findViewById(R.id.select_album_song_length);
    if (podcastDescription != null || artistInfo != null) {
        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    } else {
        String s = context.getResources().getQuantityString(R.plurals.select_album_n_songs, songCount,
                songCount);

        songCountView.setVisibility(View.GONE);
        songLengthView.setVisibility(View.GONE);
    }
}

From source file:org.sirimangalo.meditationplus.AdapterCommit.java

@Override
public View getView(final int position, View convertView, ViewGroup parent) {

    LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);

    View rowView = inflater.inflate(R.layout.list_item_commit, parent, false);

    final View shell = rowView.findViewById(R.id.detail_shell);

    rowView.setOnClickListener(new View.OnClickListener() {
        @Override/*from   w  w  w.j av a 2 s  .c  om*/
        public void onClick(View view) {
            boolean visible = shell.getVisibility() == View.VISIBLE;

            shell.setVisibility(visible ? View.GONE : View.VISIBLE);

            context.setCommitVisible(position, !visible);

        }
    });

    final JSONObject p = values.get(position);

    TextView title = (TextView) rowView.findViewById(R.id.title);
    TextView descV = (TextView) rowView.findViewById(R.id.desc);
    TextView defV = (TextView) rowView.findViewById(R.id.def);
    TextView usersV = (TextView) rowView.findViewById(R.id.users);
    TextView youV = (TextView) rowView.findViewById(R.id.you);

    try {

        if (p.getBoolean("open"))
            shell.setVisibility(View.VISIBLE);

        title.setText(p.getString("title"));
        descV.setText(p.getString("description"));

        String length = p.getString("length");
        String time = p.getString("time");
        final String cid = p.getString("cid");

        String def = "";

        boolean repeat = false;

        if (length.indexOf(":") > 0) {
            repeat = true;
            String[] lengtha = length.split(":");
            def += lengtha[0] + " minutes walking and " + lengtha[1] + " minutes sitting";
        } else
            def += length + " minutes total meditation";

        String period = p.getString("period");

        String day = p.getString("day");

        if (period.equals("daily")) {
            if (repeat)
                def += " every day";
            else
                def += " per day";
        } else if (period.equals("weekly")) {
            if (repeat)
                def += " every " + dow[Integer.parseInt(day)];
            else
                def += " per week";
        } else if (period.equals("monthly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the month";
            else
                def += " per month";
        } else if (period.equals("yearly")) {
            if (repeat)
                def += " on the " + day
                        + (day.substring(day.length() - 1).equals("1") ? "st"
                                : (day.substring(day.length() - 1).equals("2") ? "nd"
                                        : (day.substring(day.length() - 1).equals("3") ? "rd" : "th")))
                        + " day of the year";
            else
                def += " per year";
        }

        if (!time.equals("any")) {
            Calendar utc = Calendar.getInstance(TimeZone.getTimeZone("UTC"));
            utc.set(Calendar.HOUR_OF_DAY, Integer.parseInt(time.split(":")[0]));
            utc.set(Calendar.MINUTE, Integer.parseInt(time.split(":")[1]));

            Calendar here = Calendar.getInstance();
            here.setTimeInMillis(utc.getTimeInMillis());

            int hours = here.get(Calendar.HOUR_OF_DAY);
            int minutes = here.get(Calendar.MINUTE);

            def += " at " + (time.length() == 4 ? "0" : "") + time.replace(":", "") + "h UTC <i>("
                    + (hours > 12 ? hours - 12 : hours) + ":" + ((minutes < 10 ? "0" : "") + minutes) + " "
                    + (hours > 11 && hours < 24 ? "PM" : "AM") + " your time)</i>";
        }

        defV.setText(Html.fromHtml(def));

        JSONObject usersJ = p.getJSONObject("users");

        ArrayList<String> committedArray = new ArrayList<String>();

        // collect into array

        for (int i = 0; i < usersJ.names().length(); i++) {
            try {
                String j = usersJ.names().getString(i);
                String k = j;
                //                    if(j.equals(p.getString("creator")))
                //                        k = "["+j+"]";
                committedArray.add(k);
            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        String text = context.getString(R.string.committed) + " ";

        // add spans

        int committed = -1;

        int pos = text.length(); // start after "Committed: "

        text += TextUtils.join(", ", committedArray);
        Spannable span = new SpannableString(text);

        span.setSpan(new StyleSpan(Typeface.BOLD), 0, pos, Spannable.SPAN_EXCLUSIVE_EXCLUSIVE); // bold the "Online: "

        for (int i = 0; i < committedArray.size(); i++) {
            try {

                final String oneCom = committedArray.get(i);
                String userCom = usersJ.getString(oneCom);
                //String userCom = usersJ.getString(oneCom.replace("[", "").replace("]", ""));

                //if(oneCom.replace("[","").replace("]","").equals(loggedUser))
                if (oneCom.equals(loggedUser))
                    committed = Integer.parseInt(userCom);

                int end = pos + oneCom.length();

                ClickableSpan clickable = new ClickableSpan() {

                    @Override
                    public void onClick(View widget) {
                        context.showProfile(oneCom);
                    }

                };
                span.setSpan(clickable, pos, end, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);

                span.setSpan(new UnderlineSpan() {
                    public void updateDrawState(TextPaint tp) {
                        tp.setUnderlineText(false);
                    }
                }, pos, end, 0);

                String color = Utils.makeRedGreen(Integer.parseInt(userCom), true);

                span.setSpan(new ForegroundColorSpan(Color.parseColor("#FF" + color)), pos, end,
                        Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);

                pos += oneCom.length() + 2;

            } catch (JSONException e) {
                e.printStackTrace();
            }
        }

        usersV.setText(span);
        usersV.setMovementMethod(new LinkMovementMethod());

        if (loggedUser != null && loggedUser.length() > 0) {
            LinearLayout bl = (LinearLayout) rowView.findViewById(R.id.commit_buttons);
            if (!usersJ.has(loggedUser)) {
                Button commitB = new Button(context);
                commitB.setId(R.id.commit_button);
                commitB.setText(R.string.commit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("commitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            } else {
                Button commitB = new Button(context);
                commitB.setId(R.id.uncommit_button);
                commitB.setText(R.string.uncommit);
                commitB.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("uncommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB);
            }

            if (loggedUser.equals(p.getString("creator")) || context.isAdmin) {
                Button commitB2 = new Button(context);
                commitB2.setId(R.id.edit_commit_button);
                commitB2.setText(R.string.edit);
                commitB2.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        Intent i = new Intent(context, ActivityCommit.class);
                        i.putExtra("commitment", p.toString());
                        context.startActivity(i);
                    }
                });
                bl.addView(commitB2);

                Button commitB3 = new Button(context);
                commitB3.setId(R.id.uncommit_button);
                commitB3.setText(R.string.delete);
                commitB3.setOnClickListener(new View.OnClickListener() {
                    @Override
                    public void onClick(View view) {
                        ArrayList<NameValuePair> nvp = new ArrayList<NameValuePair>();
                        nvp.add(new BasicNameValuePair("full_update", "true"));

                        context.doSubmit("delcommitform_" + cid, nvp, true);
                    }
                });
                bl.addView(commitB3);
            }

        }

        if (committed > -1) {
            int color = Color.parseColor("#FF" + Utils.makeRedGreen(committed, false));
            rowView.setBackgroundColor(color);
        }

        if (committed != -1) {
            youV.setText(String.format(context.getString(R.string.you_commit_x), committed));
            youV.setVisibility(View.VISIBLE);
        }

    } catch (Exception e) {
        e.printStackTrace();
    }
    return rowView;
}

From source file:gr.scify.newsum.ui.ViewActivity.java

@Override
public void run() {
    // take the String from the TopicActivity
    Bundle extras = getIntent().getExtras();
    Category = extras.getString(CATEGORY_INTENT_VAR);

    // Make sure we have updated the data source
    NewSumUiActivity.setDataSource(this);

    // Get user sources
    String sUserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

    // get Topics from TopicActivity (avoid multiple server calls)
    TopicInfo[] tiTopics = TopicActivity.getTopics(sUserSources, Category, this);

    // Also get Topic Titles, to display to adapter
    final String[] saTopicTitles = new String[tiTopics.length];
    // Also get Topic IDs
    final String[] saTopicIDs = new String[tiTopics.length];
    // Also get Dates, in order to show in summary title
    final String[] saTopicDates = new String[tiTopics.length];
    // DeHTML titles
    for (int iCnt = 0; iCnt < tiTopics.length; iCnt++) {
        // update Titles Array
        saTopicTitles[iCnt] = Html.fromHtml(tiTopics[iCnt].getTitle()).toString();
        // update IDs Array
        saTopicIDs[iCnt] = tiTopics[iCnt].getID();
        // update Date Array
        saTopicDates[iCnt] = tiTopics[iCnt].getPrintableDate(NewSumUiActivity.getDefaultLocale());
    }/*w  w  w.  j a  v a2s. c  o  m*/
    // get the value of the TopicIDs list size (to use in swipe)
    saTopicIDsLength = saTopicIDs.length;
    final TextView title = (TextView) findViewById(R.id.title);
    // Fill topic spinner
    final ArrayAdapter<CharSequence> adapter = new ArrayAdapter<CharSequence>(this,
            android.R.layout.simple_spinner_item, saTopicTitles);

    final TextView tx = (TextView) findViewById(R.id.textView1);
    //      final float minm = tx.getTextSize();
    //      final float maxm = (minm + 24);

    // Get active topic
    int iTopicNum;
    // If we have returned from a pause
    if (iPrvSelectedItem >= 0)
        // use previous selection before pause
        iTopicNum = iPrvSelectedItem;
    // else
    else
        // use selection from topic page
        iTopicNum = extras.getInt(TOPIC_ID_INTENT_VAR);
    final int num = iTopicNum;

    // create an invisible spinner just to control the summaries of the
    // category (i will use it later on Swipe)
    final Spinner spinner = (Spinner) findViewById(R.id.spinner1);
    adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            spinner.setAdapter(adapter);

            // Scroll view init
            final ScrollView scroll = (ScrollView) findViewById(R.id.scrollView1);
            final String[] saTopicTitlesArg = saTopicTitles;
            final String[] saTopicIDsArg = saTopicIDs;
            final String[] SaTopicDatesArg = saTopicDates;

            // Add selection event
            spinner.setOnItemSelectedListener(new OnItemSelectedListener() {
                public void onItemSelected(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
                    // Changing summary
                    loading = true;
                    showWaitingDialog();
                    // Update visibility of rating bar
                    final RatingBar rb = (RatingBar) findViewById(R.id.ratingBar);
                    rb.setRating(0.0f);
                    rb.setVisibility(View.VISIBLE);
                    final TextView rateLbl = (TextView) findViewById(R.id.rateLbl);
                    rateLbl.setVisibility(View.VISIBLE);
                    scroll.scrollTo(0, 0);

                    String UserSources = Urls.getUserVisibleURLsAsString(ViewActivity.this);

                    String[] saTopicIDs = saTopicIDsArg;

                    // track summary views per category and topic title
                    if (getAnalyticsPref()) {
                        EasyTracker.getTracker().sendEvent(VIEW_SUMMARY_ACTION, Category,
                                saTopicTitlesArg[arg2], 0l);
                    }

                    if (sCustomCategory.trim().length() > 0) {
                        if (Category.equals(sCustomCategory)) {
                            Context ctxCur = NewSumUiActivity.getAppContext(ViewActivity.this);
                            String sCustomCategoryURL = ctxCur.getResources()
                                    .getString(R.string.custom_category_url);
                            // Check if specific element needs to be read
                            String sElementID = ctxCur.getResources()
                                    .getString(R.string.custom_category_elementId);
                            // If an element needs to be selected
                            if (sElementID.trim().length() > 0) {
                                try {
                                    // Check if specific element needs to be read
                                    String sViewOriginalPage = ctxCur.getResources()
                                            .getString(R.string.custom_category_visit_source);
                                    // Init text by a link to the original page
                                    sText = "<p><a href='" + sCustomCategoryURL + "'>" + sViewOriginalPage
                                            + "</a></p>";
                                    // Get document
                                    Document doc = Jsoup.connect(sCustomCategoryURL).get();
                                    // If a table
                                    Element eCur = doc.getElementById(sElementID);
                                    if (eCur.tagName().equalsIgnoreCase("table")) {
                                        // Get table rows
                                        Elements eRows = eCur.select("tr");

                                        // For each row
                                        StringBuffer sTextBuf = new StringBuffer();
                                        for (Element eCurRow : eRows) {
                                            // Append content
                                            // TODO: Use HTML if possible. Now problematic (crashes when we click on link)
                                            sTextBuf.append("<p>" + eCurRow.text() + "</p>");
                                        }
                                        // Return as string
                                        sText = sText + sTextBuf.toString();
                                    } else
                                        // else get text
                                        sText = eCur.text();

                                } catch (IOException e) {
                                    // Show unavailable text
                                    sText = ctxCur.getResources()
                                            .getString(R.string.custom_category_unavailable);
                                    e.printStackTrace();
                                }

                            } else
                                sText = Utils.getFromHttp(sCustomCategoryURL, false);
                        }

                    } else {
                        // call getSummary with (sTopicID, sUserSources). Use "All" for
                        // all Sources
                        String[] Summary = NewSumServiceClient.getSummary(saTopicIDs[arg2], UserSources);
                        // check if Summary exists, otherwise display message
                        if (Summary.length == 0) { // DONE APPLICATION HANGS, DOES NOT
                            // WORK. Updated: Probably OK
                            nothingFound = true;
                            AlertDialog.Builder al = new AlertDialog.Builder(ViewActivity.this);
                            al.setMessage(R.string.shouldReloadSummaries);
                            al.setNeutralButton("Ok", new DialogInterface.OnClickListener() {
                                public void onClick(DialogInterface arg0, int arg1) {
                                    // Reset cache
                                    CacheController.clearCache();
                                    // Restart main activity
                                    startActivity(new Intent(getApplicationContext(), NewSumUiActivity.class)
                                            .setFlags(Intent.FLAG_ACTIVITY_CLEAR_TOP));
                                }
                            });
                            al.setCancelable(false);
                            al.show();
                            // Return to home activity
                            loading = false;
                            return;
                        }
                        // Generate Summary text for normal categories
                        sText = generateSummaryText(Summary, ViewActivity.this);
                        pText = generatesummarypost(Summary, ViewActivity.this);
                    }

                    // Update HTML
                    tx.setText(Html.fromHtml(sText));
                    // Allow links to be followed into browser
                    tx.setMovementMethod(LinkMovementMethod.getInstance());
                    // Also Add Date to Topic Title inside Summary
                    title.setText(saTopicTitlesArg[arg2] + " : " + SaTopicDatesArg[arg2]);

                    // Update size
                    updateTextSize();

                    // Update visited topics
                    TopicActivity.addVisitedTopicID(saTopicIDs[arg2]);
                    // Done
                    loading = false;
                    closeWaitingDialog();
                }

                @Override
                public void onNothingSelected(AdapterView<?> arg0) {
                }

            });

            runOnUiThread(new Runnable() {

                @Override
                public void run() {
                    // Get active topic
                    spinner.setSelection(num);
                }
            });

        }
    });

    runOnUiThread(new Runnable() {

        @Override
        public void run() {
            showHelpDialog();
        }
    });

    closeWaitingDialog();
}

From source file:org.telegram.ui.PassportActivity.java

@Override
public View createView(Context context) {

    actionBar.setBackButtonImage(R.drawable.ic_ab_back);
    actionBar.setAllowOverlayTitle(true);

    actionBar.setActionBarMenuOnItemClick(new ActionBar.ActionBarMenuOnItemClick() {

        private boolean onIdentityDone(Runnable finishRunnable, ErrorRunnable errorRunnable) {
            if (!uploadingDocuments.isEmpty() || checkFieldsForError()) {
                return false;
            }//from  ww  w.j  ava 2  s.c  o  m
            if (allowNonLatinName) {
                allowNonLatinName = false;
                boolean error = false;
                for (int a = 0; a < nonLatinNames.length; a++) {
                    if (nonLatinNames[a]) {
                        inputFields[a].setErrorText(LocaleController.getString("PassportUseLatinOnly",
                                R.string.PassportUseLatinOnly));
                        if (!error) {
                            error = true;
                            String firstName = nonLatinNames[0]
                                    ? getTranslitString(
                                            inputExtraFields[FIELD_NATIVE_NAME].getText().toString())
                                    : inputFields[FIELD_NAME].getText().toString();
                            String middleName = nonLatinNames[1]
                                    ? getTranslitString(
                                            inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString())
                                    : inputFields[FIELD_MIDNAME].getText().toString();
                            String lastName = nonLatinNames[2]
                                    ? getTranslitString(
                                            inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString())
                                    : inputFields[FIELD_SURNAME].getText().toString();

                            if (!TextUtils.isEmpty(firstName) && !TextUtils.isEmpty(middleName)
                                    && !TextUtils.isEmpty(lastName)) {
                                int num = a;
                                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                                builder.setMessage(LocaleController.formatString("PassportNameCheckAlert",
                                        R.string.PassportNameCheckAlert, firstName, middleName, lastName));
                                builder.setTitle(LocaleController.getString("AppName", R.string.AppName));
                                builder.setPositiveButton(LocaleController.getString("Done", R.string.Done),
                                        (dialogInterface, i) -> {
                                            inputFields[FIELD_NAME].setText(firstName);
                                            inputFields[FIELD_MIDNAME].setText(middleName);
                                            inputFields[FIELD_SURNAME].setText(lastName);
                                            showEditDoneProgress(true, true);
                                            onIdentityDone(finishRunnable, errorRunnable);
                                        });
                                builder.setNegativeButton(LocaleController.getString("Edit", R.string.Edit),
                                        (dialogInterface, i) -> onFieldError(inputFields[num]));
                                showDialog(builder.create());
                            } else {
                                onFieldError(inputFields[a]);
                            }
                        }
                    }
                }
                if (error) {
                    return false;
                }
            }
            if (isHasNotAnyChanges()) {
                finishFragment();
                return false;
            }
            JSONObject json = null;
            JSONObject documentsJson = null;
            try {
                if (!documentOnly) {
                    HashMap<String, String> valuesToSave = new HashMap<>(currentValues);
                    if (currentType.native_names) {
                        if (nativeInfoCell.getVisibility() == View.VISIBLE) {
                            valuesToSave.put("first_name_native",
                                    inputExtraFields[FIELD_NATIVE_NAME].getText().toString());
                            valuesToSave.put("middle_name_native",
                                    inputExtraFields[FIELD_NATIVE_MIDNAME].getText().toString());
                            valuesToSave.put("last_name_native",
                                    inputExtraFields[FIELD_NATIVE_SURNAME].getText().toString());
                        } else {
                            valuesToSave.put("first_name_native",
                                    inputFields[FIELD_NATIVE_NAME].getText().toString());
                            valuesToSave.put("middle_name_native",
                                    inputFields[FIELD_NATIVE_MIDNAME].getText().toString());
                            valuesToSave.put("last_name_native",
                                    inputFields[FIELD_NATIVE_SURNAME].getText().toString());
                        }
                    }
                    valuesToSave.put("first_name", inputFields[FIELD_NAME].getText().toString());
                    valuesToSave.put("middle_name", inputFields[FIELD_MIDNAME].getText().toString());
                    valuesToSave.put("last_name", inputFields[FIELD_SURNAME].getText().toString());
                    valuesToSave.put("birth_date", inputFields[FIELD_BIRTHDAY].getText().toString());
                    valuesToSave.put("gender", currentGender);
                    valuesToSave.put("country_code", currentCitizeship);
                    valuesToSave.put("residence_country_code", currentResidence);

                    json = new JSONObject();
                    ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet());
                    Collections.sort(keys, (key1, key2) -> {
                        int val1 = getFieldCost(key1);
                        int val2 = getFieldCost(key2);
                        if (val1 < val2) {
                            return -1;
                        } else if (val1 > val2) {
                            return 1;
                        }
                        return 0;
                    });
                    for (int a = 0, size = keys.size(); a < size; a++) {
                        String key = keys.get(a);
                        json.put(key, valuesToSave.get(key));
                    }
                }

                if (currentDocumentsType != null) {
                    HashMap<String, String> valuesToSave = new HashMap<>(currentDocumentValues);
                    valuesToSave.put("document_no", inputFields[FIELD_CARDNUMBER].getText().toString());
                    if (currentExpireDate[0] != 0) {
                        valuesToSave.put("expiry_date", String.format(Locale.US, "%02d.%02d.%d",
                                currentExpireDate[2], currentExpireDate[1], currentExpireDate[0]));
                    } else {
                        valuesToSave.put("expiry_date", "");
                    }

                    documentsJson = new JSONObject();
                    ArrayList<String> keys = new ArrayList<>(valuesToSave.keySet());
                    Collections.sort(keys, (key1, key2) -> {
                        int val1 = getFieldCost(key1);
                        int val2 = getFieldCost(key2);
                        if (val1 < val2) {
                            return -1;
                        } else if (val1 > val2) {
                            return 1;
                        }
                        return 0;
                    });
                    for (int a = 0, size = keys.size(); a < size; a++) {
                        String key = keys.get(a);
                        documentsJson.put(key, valuesToSave.get(key));
                    }
                }
            } catch (Exception ignore) {

            }
            if (fieldsErrors != null) {
                fieldsErrors.clear();
            }
            if (documentsErrors != null) {
                documentsErrors.clear();
            }
            delegate.saveValue(currentType, null, json != null ? json.toString() : null, currentDocumentsType,
                    documentsJson != null ? documentsJson.toString() : null, null, selfieDocument,
                    translationDocuments, frontDocument,
                    reverseLayout != null && reverseLayout.getVisibility() == View.VISIBLE ? reverseDocument
                            : null,
                    finishRunnable, errorRunnable);
            return true;
        }

        @Override
        public void onItemClick(int id) {
            if (id == -1) {
                if (checkDiscard()) {
                    return;
                }
                if (currentActivityType == TYPE_REQUEST || currentActivityType == TYPE_PASSWORD) {
                    callCallback(false);
                }
                finishFragment();
            } else if (id == info_item) {
                if (getParentActivity() == null) {
                    return;
                }
                final TextView message = new TextView(getParentActivity());
                String str2 = LocaleController.getString("PassportInfo2", R.string.PassportInfo2);
                SpannableStringBuilder spanned = new SpannableStringBuilder(str2);
                int index1 = str2.indexOf('*');
                int index2 = str2.lastIndexOf('*');
                if (index1 != -1 && index2 != -1) {
                    spanned.replace(index2, index2 + 1, "");
                    spanned.replace(index1, index1 + 1, "");
                    spanned.setSpan(new URLSpanNoUnderline(
                            LocaleController.getString("PassportInfoUrl", R.string.PassportInfoUrl)) {
                        @Override
                        public void onClick(View widget) {
                            dismissCurrentDialig();
                            super.onClick(widget);
                        }
                    }, index1, index2 - 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                }
                message.setText(spanned);
                message.setTextSize(TypedValue.COMPLEX_UNIT_DIP, 16);
                message.setLinkTextColor(Theme.getColor(Theme.key_dialogTextLink));
                message.setHighlightColor(Theme.getColor(Theme.key_dialogLinkSelection));
                message.setPadding(AndroidUtilities.dp(23), 0, AndroidUtilities.dp(23), 0);
                message.setMovementMethod(new AndroidUtilities.LinkMovementMethodMy());
                message.setTextColor(Theme.getColor(Theme.key_dialogTextBlack));

                AlertDialog.Builder builder = new AlertDialog.Builder(getParentActivity());
                builder.setView(message);
                builder.setTitle(LocaleController.getString("PassportInfoTitle", R.string.PassportInfoTitle));
                builder.setNegativeButton(LocaleController.getString("Close", R.string.Close), null);
                showDialog(builder.create());
            } else if (id == done_button) {
                if (currentActivityType == TYPE_PASSWORD) {
                    onPasswordDone(false);
                    return;
                }
                if (currentActivityType == TYPE_PHONE_VERIFICATION) {
                    views[currentViewNum].onNextPressed();
                } else {
                    final Runnable finishRunnable = () -> finishFragment();
                    final ErrorRunnable errorRunnable = new ErrorRunnable() {
                        @Override
                        public void onError(String error, String text) {
                            if ("PHONE_VERIFICATION_NEEDED".equals(error)) {
                                startPhoneVerification(true, text, finishRunnable, this, delegate);
                            } else {
                                showEditDoneProgress(true, false);
                            }
                        }
                    };

                    if (currentActivityType == TYPE_EMAIL) {
                        String value;
                        if (useCurrentValue) {
                            value = currentEmail;
                        } else {
                            if (checkFieldsForError()) {
                                return;
                            }
                            value = inputFields[FIELD_EMAIL].getText().toString();
                        }
                        delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null,
                                finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_PHONE) {
                        String value;
                        if (useCurrentValue) {
                            value = UserConfig.getInstance(currentAccount).getCurrentUser().phone;
                        } else {
                            if (checkFieldsForError()) {
                                return;
                            }
                            value = inputFields[FIELD_PHONECODE].getText().toString()
                                    + inputFields[FIELD_PHONE].getText().toString();
                        }
                        delegate.saveValue(currentType, value, null, null, null, null, null, null, null, null,
                                finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_ADDRESS) {
                        if (!uploadingDocuments.isEmpty() || checkFieldsForError()) {
                            return;
                        }
                        if (isHasNotAnyChanges()) {
                            finishFragment();
                            return;
                        }
                        JSONObject json = null;
                        try {
                            if (!documentOnly) {
                                json = new JSONObject();
                                json.put("street_line1", inputFields[FIELD_STREET1].getText().toString());
                                json.put("street_line2", inputFields[FIELD_STREET2].getText().toString());
                                json.put("post_code", inputFields[FIELD_POSTCODE].getText().toString());
                                json.put("city", inputFields[FIELD_CITY].getText().toString());
                                json.put("state", inputFields[FIELD_STATE].getText().toString());
                                json.put("country_code", currentCitizeship);
                            }
                        } catch (Exception ignore) {

                        }
                        if (fieldsErrors != null) {
                            fieldsErrors.clear();
                        }
                        if (documentsErrors != null) {
                            documentsErrors.clear();
                        }
                        delegate.saveValue(currentType, null, json != null ? json.toString() : null,
                                currentDocumentsType, null, documents, selfieDocument, translationDocuments,
                                null, null, finishRunnable, errorRunnable);
                    } else if (currentActivityType == TYPE_IDENTITY) {
                        if (!onIdentityDone(finishRunnable, errorRunnable)) {
                            return;
                        }
                    } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) {
                        final TLRPC.TL_account_verifyEmail req = new TLRPC.TL_account_verifyEmail();
                        req.email = currentValues.get("email");
                        req.code = inputFields[FIELD_EMAIL].getText().toString();
                        int reqId = ConnectionsManager.getInstance(currentAccount).sendRequest(req,
                                (response, error) -> AndroidUtilities.runOnUIThread(() -> {
                                    if (error == null) {
                                        delegate.saveValue(currentType, currentValues.get("email"), null, null,
                                                null, null, null, null, null, null, finishRunnable,
                                                errorRunnable);
                                    } else {
                                        AlertsCreator.processError(currentAccount, error, PassportActivity.this,
                                                req);
                                        errorRunnable.onError(null, null);
                                    }
                                }));
                        ConnectionsManager.getInstance(currentAccount).bindRequestToGuid(reqId, classGuid);
                    }
                    showEditDoneProgress(true, true);
                }
            }
        }
    });

    if (currentActivityType == TYPE_PHONE_VERIFICATION) {
        fragmentView = scrollView = new ScrollView(context) {
            @Override
            protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
                return false;
            }

            @Override
            public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
                if (currentViewNum == 1 || currentViewNum == 2 || currentViewNum == 4) {
                    rectangle.bottom += AndroidUtilities.dp(40);
                }
                return super.requestChildRectangleOnScreen(child, rectangle, immediate);
            }

            @Override
            protected void onMeasure(int widthMeasureSpec, int heightMeasureSpec) {
                scrollHeight = MeasureSpec.getSize(heightMeasureSpec) - AndroidUtilities.dp(30);
                super.onMeasure(widthMeasureSpec, heightMeasureSpec);
            }
        };
        scrollView.setFillViewport(true);
        AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault));
    } else {
        fragmentView = new FrameLayout(context);
        FrameLayout frameLayout = (FrameLayout) fragmentView;
        fragmentView.setBackgroundColor(Theme.getColor(Theme.key_windowBackgroundGray));

        scrollView = new ScrollView(context) {
            @Override
            protected boolean onRequestFocusInDescendants(int direction, Rect previouslyFocusedRect) {
                return false;
            }

            @Override
            public boolean requestChildRectangleOnScreen(View child, Rect rectangle, boolean immediate) {
                rectangle.offset(child.getLeft() - child.getScrollX(), child.getTop() - child.getScrollY());
                rectangle.top += AndroidUtilities.dp(20);
                rectangle.bottom += AndroidUtilities.dp(50);
                return super.requestChildRectangleOnScreen(child, rectangle, immediate);
            }
        };
        scrollView.setFillViewport(true);
        AndroidUtilities.setScrollViewEdgeEffectColor(scrollView, Theme.getColor(Theme.key_actionBarDefault));
        frameLayout.addView(scrollView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT,
                        Gravity.LEFT | Gravity.TOP, 0, 0, 0, currentActivityType == TYPE_REQUEST ? 48 : 0));

        linearLayout2 = new LinearLayout(context);
        linearLayout2.setOrientation(LinearLayout.VERTICAL);
        scrollView.addView(linearLayout2, new ScrollView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT,
                ViewGroup.LayoutParams.WRAP_CONTENT));
    }

    if (currentActivityType != TYPE_REQUEST && currentActivityType != TYPE_MANAGE) {
        ActionBarMenu menu = actionBar.createMenu();
        doneItem = menu.addItemWithWidth(done_button, R.drawable.ic_done, AndroidUtilities.dp(56));
        progressView = new ContextProgressView(context, 1);
        progressView.setAlpha(0.0f);
        progressView.setScaleX(0.1f);
        progressView.setScaleY(0.1f);
        progressView.setVisibility(View.INVISIBLE);
        doneItem.addView(progressView,
                LayoutHelper.createFrame(LayoutHelper.MATCH_PARENT, LayoutHelper.MATCH_PARENT));

        if (currentActivityType == TYPE_IDENTITY || currentActivityType == TYPE_ADDRESS) {
            if (chatAttachAlert != null) {
                try {
                    if (chatAttachAlert.isShowing()) {
                        chatAttachAlert.dismiss();
                    }
                } catch (Exception ignore) {

                }
                chatAttachAlert.onDestroy();
                chatAttachAlert = null;
            }
        }
    }

    if (currentActivityType == TYPE_PASSWORD) {
        createPasswordInterface(context);
    } else if (currentActivityType == TYPE_REQUEST) {
        createRequestInterface(context);
    } else if (currentActivityType == TYPE_IDENTITY) {
        createIdentityInterface(context);
        fillInitialValues();
    } else if (currentActivityType == TYPE_ADDRESS) {
        createAddressInterface(context);
        fillInitialValues();
    } else if (currentActivityType == TYPE_PHONE) {
        createPhoneInterface(context);
    } else if (currentActivityType == TYPE_EMAIL) {
        createEmailInterface(context);
    } else if (currentActivityType == TYPE_EMAIL_VERIFICATION) {
        createEmailVerificationInterface(context);
    } else if (currentActivityType == TYPE_PHONE_VERIFICATION) {
        createPhoneVerificationInterface(context);
    } else if (currentActivityType == TYPE_MANAGE) {
        createManageInterface(context);
    }
    return fragmentView;
}