Example usage for android.widget EditText setSelection

List of usage examples for android.widget EditText setSelection

Introduction

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

Prototype

public void setSelection(int start, int stop) 

Source Link

Document

Convenience for Selection#setSelection(Spannable,int,int) .

Usage

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceTimeProfile.java

private void restoreViewContents(final SavedViewContents sv) {
    final EditText dlg_prof_name_et = (EditText) mDialog.findViewById(R.id.edit_profile_time_profile_et_name);
    final CheckBox cb_active = (CheckBox) mDialog.findViewById(R.id.edit_profile_time_enabled);
    final Spinner spinnerDateTimeType = (Spinner) mDialog.findViewById(R.id.edit_profile_time_date_time_type);
    final Spinner spinnerYear = (Spinner) mDialog.findViewById(R.id.edit_profile_time_exec_year);
    final Spinner spinnerMonth = (Spinner) mDialog.findViewById(R.id.edit_profile_time_exec_month);
    final Spinner spinnerDay = (Spinner) mDialog.findViewById(R.id.edit_profile_time_exec_day);
    final Spinner spinnerHour = (Spinner) mDialog.findViewById(R.id.edit_profile_time_exec_hours);
    final Spinner spinnerMin = (Spinner) mDialog.findViewById(R.id.edit_profile_time_exec_minutes);

    Handler hndl1 = new Handler();
    hndl1.postDelayed(new Runnable() {
        @Override//from w ww.j ava  2s.  c  o m
        public void run() {
            dlg_prof_name_et.setText(sv.dlg_prof_name_et);
            dlg_prof_name_et.setSelection(sv.dlg_prof_name_et_spos, sv.dlg_prof_name_et_epos);
            cb_active.setChecked(sv.cb_active);

            spinnerDateTimeType.setSelection(sv.spinnerDateTimeType);
            spinnerYear.setSelection(sv.spinnerYear);
            spinnerMonth.setSelection(sv.spinnerMonth);
            spinnerDay.setSelection(sv.spinnerDay);
            spinnerHour.setSelection(sv.spinnerHour);
            spinnerMin.setSelection(sv.spinnerMin);
            setDayOfTheWeekCheckBox(mGlblParms, mDialog, sv.day_of_the_week);
            Handler hndl2 = new Handler();
            hndl2.postDelayed(new Runnable() {
                @Override
                public void run() {
                }
            }, 50);
        }
    }, 50);
}

From source file:com.songcode.materialnotes.ui.NotesListActivity.java

private void showCreateOrModifyFolderDialog(final boolean create) {
    final AlertDialog.Builder builder = new AlertDialog.Builder(this);
    View view = LayoutInflater.from(this).inflate(R.layout.dialog_edit_text, null);
    final EditText etName = (EditText) view.findViewById(R.id.et_foler_name);
    showSoftInput();/*  w ww.j a  v a2s .  c  o m*/
    if (!create) {
        if (mFocusNoteDataItem != null) {
            etName.setText(mFocusNoteDataItem.getSnippet());
            builder.setTitle(getString(R.string.menu_folder_change_name));
        } else {
            Log.e(TAG, "The long click data item is null");
            return;
        }
    } else {
        etName.setText("");
        builder.setTitle(this.getString(R.string.menu_create_folder));
    }

    builder.setPositiveButton(android.R.string.ok, null);
    builder.setNegativeButton(android.R.string.cancel, new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int which) {
            hideSoftInput(etName);
        }
    });

    final Dialog dialog = builder.setView(view).show();
    final Button positive = (Button) dialog.findViewById(android.R.id.button1);
    positive.setOnClickListener(new OnClickListener() {
        public void onClick(View v) {
            hideSoftInput(etName);
            String name = etName.getText().toString();
            if (DataUtils.checkVisibleFolderName(mContentResolver, name)) {
                Toast.makeText(NotesListActivity.this, getString(R.string.folder_exist, name),
                        Toast.LENGTH_LONG).show();
                etName.setSelection(0, etName.length());
                return;
            }
            if (!create) {
                if (!TextUtils.isEmpty(name)) {
                    ContentValues values = new ContentValues();
                    values.put(NoteColumns.SNIPPET, name);
                    values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                    values.put(NoteColumns.LOCAL_MODIFIED, 1);
                    mContentResolver.update(Notes.CONTENT_NOTE_URI, values, NoteColumns.ID + "=?",
                            new String[] { String.valueOf(mFocusNoteDataItem.getId()) });
                }
            } else if (!TextUtils.isEmpty(name)) {
                ContentValues values = new ContentValues();
                values.put(NoteColumns.SNIPPET, name);
                values.put(NoteColumns.TYPE, Notes.TYPE_FOLDER);
                mContentResolver.insert(Notes.CONTENT_NOTE_URI, values);
            }
            dialog.dismiss();
        }
    });

    if (TextUtils.isEmpty(etName.getText())) {
        positive.setEnabled(false);
    }
    /**
     * When the name edit text is null, disable the positive button
     */
    etName.addTextChangedListener(new TextWatcher() {
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
            // TODO Auto-generated method stub

        }

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (TextUtils.isEmpty(etName.getText())) {
                positive.setEnabled(false);
            } else {
                positive.setEnabled(true);
            }
        }

        public void afterTextChanged(Editable s) {
            // TODO Auto-generated method stub

        }
    });
}

From source file:com.httrack.android.HTTrackActivity.java

/** Set current focus identifier. **/
private void setCurrentFocusId(final int ids[]) {
    if (ids != null && ids.length != 0) {
        final int id = ids[0];
        final View view = findViewById(id);
        if (view != null) {
            view.requestFocus();//from  ww  w  .  j a  va2 s.  c  om
            if (view instanceof EditText) {
                final EditText edit = EditText.class.cast(view);
                if (ids.length >= 3) {
                    final int start = ids[1];
                    final int end = ids[2];
                    edit.setSelection(start, end);
                }
            }
        }
    }
}

From source file:org.cryptsecure.Utility.java

/**
 * Smart paste some pasteText into an editText. Remember the position (i)
 * and jump behind the pastedText afterwards if not jumpToEnd is selected.
 * If selectAfterPaste is set then select the pasted text.
 * /*w w w  .  j  a  va  2  s.  co m*/
 * 
 * @param editText
 *            the edit text
 * @param pasteText
 *            the paste text
 * @param ensureBefore
 *            the ensure before
 * @param ensureAfter
 *            the ensure after
 * @param jumpToEnd
 *            the jump to end
 */
public static void smartPaste(EditText editText, String pasteText, String ensureBefore, String ensureAfter,
        boolean jumpToEnd, boolean selectAfterPaste, boolean ensureBeforeOnlyIfNotBeginning) {
    // messageText.getText().append(textualSmiley);
    // if text was selected replace the text
    int i = editText.getSelectionStart();
    int e = editText.getSelectionEnd();
    String prevText = editText.getText().toString();
    if (i < 0) {
        // default fallback is concatenation
        if (!prevText.endsWith(ensureBefore)) {
            if (!ensureBeforeOnlyIfNotBeginning || prevText.length() > 0) {
                prevText = prevText.concat(ensureBefore);
            }
        }
        editText.setText(prevText + pasteText + ensureAfter);
    } else {
        // otherwise try to fill in the text
        String text1 = prevText.substring(0, i);
        if (!text1.endsWith(ensureBefore)) {
            if (!ensureBeforeOnlyIfNotBeginning || prevText.length() > 0) {
                text1 = text1.concat(ensureBefore);
            }
        }
        if (e < 0) {
            e = i;
        }
        String text2 = prevText.substring(e);
        if (!text2.startsWith(ensureAfter)) {
            text2 = ensureAfter + text2;
        }
        editText.setText(text1.concat(pasteText).concat(text2));
    }
    if (selectAfterPaste) {
        editText.setSelection(i, i + pasteText.length());
    } else if (jumpToEnd) {
        editText.setSelection(editText.getText().length());
    } else {
        editText.setSelection(i);
    }
}

From source file:org.yaaic.fragment.ConversationFragment.java

/**
 * Complete a nick in the input line/*from w  ww.ja v  a  2s.  com*/
 */
private void doNickCompletion(EditText input) {
    String text = input.getText().toString();

    if (text.length() <= 0) {
        return;
    }

    String[] tokens = text.split("[\\s,.-]+");

    if (tokens.length <= 0) {
        return;
    }

    String word = tokens[tokens.length - 1].toLowerCase();
    tokens[tokens.length - 1] = null;

    int begin = input.getSelectionStart();
    int end = input.getSelectionEnd();
    int cursor = Math.min(begin, end);
    int sel_end = Math.max(begin, end);

    boolean in_selection = (cursor != sel_end);

    if (in_selection) {
        word = text.substring(cursor, sel_end);
    } else {
        // use the word at the curent cursor position
        while (true) {
            cursor -= 1;
            if (cursor <= 0 || text.charAt(cursor) == ' ') {
                break;
            }
        }

        if (cursor < 0) {
            cursor = 0;
        }

        if (text.charAt(cursor) == ' ') {
            cursor += 1;
        }

        sel_end = text.indexOf(' ', cursor);

        if (sel_end == -1) {
            sel_end = text.length();
        }

        word = text.substring(cursor, sel_end);
    }
    // Log.d("Yaaic", "Trying to complete nick: " + word);

    Conversation conversationForUserList = pagerAdapter.getItem(pager.getCurrentItem());

    String[] users = null;

    if (conversationForUserList.getType() == Conversation.TYPE_CHANNEL) {
        users = binder.getService().getConnection(server.getId())
                .getUsersAsStringArray(conversationForUserList.getName());
    }

    // go through users and add matches
    if (users != null) {
        List<Integer> result = new ArrayList<Integer>();

        for (int i = 0; i < users.length; i++) {
            String nick = removeStatusChar(users[i].toLowerCase());
            if (nick.startsWith(word.toLowerCase())) {
                result.add(Integer.valueOf(i));
            }
        }

        if (result.size() == 1) {
            input.setSelection(cursor, sel_end);
            insertNickCompletion(input, users[result.get(0).intValue()]);
        } else if (result.size() > 0) {
            Intent intent = new Intent(getActivity(), UsersActivity.class);
            String[] extra = new String[result.size()];
            int i = 0;

            for (Integer n : result) {
                extra[i++] = users[n.intValue()];
            }

            input.setSelection(cursor, sel_end);
            intent.putExtra(Extra.USERS, extra);
            startActivityForResult(intent, REQUEST_CODE_NICK_COMPLETION);
        }
    }
}

From source file:ir.occc.android.irc.activity.ConversationActivity.java

/**
 * Complete a nick in the input line//from ww w .  j av a  2s  .  c  om
 */
private void doNickCompletion(EditText input) {
    String text = input.getText().toString();

    if (text.length() <= 0) {
        return;
    }

    String[] tokens = text.split("[\\s,.-]+");

    if (tokens.length <= 0) {
        return;
    }

    String word = tokens[tokens.length - 1].toLowerCase();
    tokens[tokens.length - 1] = null;

    int begin = input.getSelectionStart();
    int end = input.getSelectionEnd();
    int cursor = Math.min(begin, end);
    int sel_end = Math.max(begin, end);

    boolean in_selection = (cursor != sel_end);

    if (in_selection) {
        word = text.substring(cursor, sel_end);
    } else {
        // use the word at the curent cursor position
        while (true) {
            cursor -= 1;
            if (cursor <= 0 || text.charAt(cursor) == ' ') {
                break;
            }
        }

        if (cursor < 0) {
            cursor = 0;
        }

        if (text.charAt(cursor) == ' ') {
            cursor += 1;
        }

        sel_end = text.indexOf(' ', cursor);

        if (sel_end == -1) {
            sel_end = text.length();
        }

        word = text.substring(cursor, sel_end);
    }
    // Log.d("Yaaic", "Trying to complete nick: " + word);

    Conversation conversationForUserList = pagerAdapter.getItem(pager.getCurrentItem());

    String[] users = null;

    if (conversationForUserList.getType() == Conversation.TYPE_CHANNEL) {
        users = binder.getService().getConnection(server.getId())
                .getUsersAsStringArray(conversationForUserList.getName());
    }

    // go through users and add matches
    if (users != null) {
        List<Integer> result = new ArrayList<Integer>();

        for (int i = 0; i < users.length; i++) {
            String nick = removeStatusChar(users[i].toLowerCase());
            if (nick.startsWith(word.toLowerCase())) {
                result.add(Integer.valueOf(i));
            }
        }

        if (result.size() == 1) {
            input.setSelection(cursor, sel_end);
            insertNickCompletion(input, users[result.get(0).intValue()]);
        } else if (result.size() > 0) {
            Intent intent = new Intent(this, UsersActivity.class);
            String[] extra = new String[result.size()];
            int i = 0;

            for (Integer n : result) {
                extra[i++] = users[n.intValue()];
            }

            input.setSelection(cursor, sel_end);
            intent.putExtra(Extra.USERS, extra);
            startActivityForResult(intent, REQUEST_CODE_NICK_COMPLETION);
        }
    }
}

From source file:com.sentaroh.android.TaskAutomation.Config.ProfileMaintenanceTaskProfile.java

private void restoreViewContents(final SavedViewContents sv) {
    final EditText dlg_prof_name_et = (EditText) mDialog.findViewById(R.id.edit_profile_task_profile_et_name);
    final CheckBox cb_active = (CheckBox) mDialog.findViewById(R.id.edit_profile_task_enabled);
    final CheckBox cb_notification = (CheckBox) mDialog.findViewById(R.id.edit_profile_task_error_notification);
    final Spinner spinnerTriggerCat = (Spinner) mDialog
            .findViewById(R.id.edit_profile_task_exec_trigger_category);
    final Spinner spinnerEvent = (Spinner) mDialog.findViewById(R.id.edit_profile_task_exec_trigger_event);
    final CheckBox cb_enable_env_parms = (CheckBox) mDialog
            .findViewById(R.id.edit_profile_task_enable_env_parms);
    final Spinner spinnerActionProfile = (Spinner) mDialog.findViewById(R.id.edit_profile_task_user_actionlist);
    final Spinner spinnerBuiltinPrimitiveAction = (Spinner) mDialog
            .findViewById(R.id.edit_profile_task_builtin_primitive_actionlist);
    final Spinner spinnerBuiltinConditionalAction = (Spinner) mDialog
            .findViewById(R.id.edit_profile_task_builtin_conditional_actionlist);
    final Spinner spinnerBuiltinCancelAction = (Spinner) mDialog
            .findViewById(R.id.edit_profile_task_builtin_cancel_actionlist);
    final Spinner spinnerBuiltinBlockAction = (Spinner) mDialog
            .findViewById(R.id.edit_profile_task_builtin_block_actionlist);
    final ListView lv_act_list = (ListView) mDialog.findViewById(android.R.id.list);
    final Spinner spinnerSelectAction = (Spinner) mDialog.findViewById(R.id.edit_profile_task_select_action);

    Handler hndl1 = new Handler();
    hndl1.postDelayed(new Runnable() {
        @Override/*from  ww  w. j  ava2s .c o  m*/
        public void run() {
            dlg_prof_name_et.setText(sv.dlg_prof_name_et);
            dlg_prof_name_et.setSelection(sv.dlg_prof_name_et_spos, sv.dlg_prof_name_et_epos);
            cb_active.setChecked(sv.cb_active);
            cb_notification.setChecked(sv.cb_notification);
            if (spinnerTriggerCat.getSelectedItemPosition() != sv.spinnerTriggerCat) {
                spinnerTriggerCat.setSelection(sv.spinnerTriggerCat);
            }
            Handler hndl2 = new Handler();
            hndl2.postDelayed(new Runnable() {
                @Override
                public void run() {
                    spinnerEvent.setSelection(sv.spinnerEvent);

                    lv_act_list.setSelectionFromTop(sv.lv_act_list[0], sv.lv_act_list[1]);
                    for (int i = 0; i < mGlblParms.taskActionListAdapter.getCount(); i++)
                        mGlblParms.taskActionListAdapter.remove(0);
                    for (int i = 0; i < sv.action_adapter_list.size(); i++)
                        mGlblParms.taskActionListAdapter.add(sv.action_adapter_list.get(i));
                    mGlblParms.taskActionListAdapter.notifyDataSetChanged();
                }
            }, 50);
            cb_enable_env_parms.setChecked(sv.cb_enable_env_parms);

            spinnerActionProfile.setSelection(sv.spinnerActionProfile);
            spinnerBuiltinPrimitiveAction.setSelection(sv.spinnerBuiltinPrimitiveAction);
            spinnerBuiltinConditionalAction.setSelection(sv.spinnerBuiltinConditionalAction);
            spinnerBuiltinCancelAction.setSelection(sv.spinnerBuiltinCancelAction);
            spinnerBuiltinBlockAction.setSelection(sv.spinnerBuiltinBlockAction);
            spinnerSelectAction.setSelection(sv.spinnerSelectAction);
        }
    }, 50);
}

From source file:indrora.atomic.activity.ConversationActivity.java

/**
 * Complete a nick in the input line//  w ww. j a va  2 s  .  c o  m
 */
private void doNickCompletion(EditText input) {
    String text = input.getText().toString();

    if (text.length() <= 0) {
        return;
    }

    String[] tokens = text.split("[\\s,.-]+");

    if (tokens.length <= 0) {
        return;
    }

    String word = tokens[tokens.length - 1].toLowerCase(Locale.US);
    tokens[tokens.length - 1] = null;

    int begin = input.getSelectionStart();
    int end = input.getSelectionEnd();
    int cursor = Math.min(begin, end);
    int sel_end = Math.max(begin, end);

    boolean in_selection = (cursor != sel_end);

    if (in_selection) {
        word = text.substring(cursor, sel_end);
    } else {
        // use the word at the curent cursor position
        while (true) {
            cursor -= 1;
            if (cursor <= 0 || text.charAt(cursor) == ' ') {
                break;
            }
        }

        if (cursor < 0) {
            cursor = 0;
        }

        if (text.charAt(cursor) == ' ') {
            cursor += 1;
        }

        sel_end = text.indexOf(' ', cursor);

        if (sel_end == -1) {
            sel_end = text.length();
        }

        word = text.substring(cursor, sel_end);
    }
    // Log.d("Yaaic", "Trying to complete nick: " + word);

    Conversation conversationForUserList = pagerAdapter.getItem(pager.getCurrentItem());

    String[] users = null;

    if (conversationForUserList.getType() == Conversation.TYPE_CHANNEL) {
        users = binder.getService().getConnection(server.getId())
                .getUsersAsStringArray(conversationForUserList.getName());
    }

    // go through users and add matches
    if (users != null) {
        final List<Integer> result = new ArrayList<Integer>();

        for (int i = 0; i < users.length; i++) {
            String nick = removeStatusChar(users[i].toLowerCase(Locale.US));
            if (nick.startsWith(word.toLowerCase(Locale.US))) {
                result.add(Integer.valueOf(i));
            }
        }

        if (result.size() == 1) {
            input.setSelection(cursor, sel_end);
            insertNickCompletion(input, users[result.get(0).intValue()]);
        } else if (result.size() > 0) {
            // There was an ambiguity. Choose who wins.
            // in yaaic, this was 80% handled by an external intent.
            // I find that inelegant, since we can handle it here and win on
            // low-resource
            // devices (e.g. the Moto Triumph).
            // This uses more of the android native resources, being a
            // little less break-y.
            final EditText finput = input;
            final int fCursor = cursor;
            final int fSelEnd = sel_end;
            AlertDialog.Builder b = new Builder(this);
            b.setTitle("Disambiguation");

            // Get the possible users.
            final String[] extra = new String[result.size()];
            int i = 0;
            for (Integer n : result) {
                extra[i++] = users[n.intValue()];
            }
            // Now, take that list of possible user and let someone choose
            // who wins.
            b.setItems(extra, new OnClickListener() {

                @Override
                public void onClick(DialogInterface dialog, int which) {
                    finput.setSelection(fCursor, fSelEnd);
                    insertNickCompletion((EditText) findViewById(R.id.input), extra[which]);

                }
            });
            // And show that selection.
            b.show();
        }
    }
}

From source file:com.sentaroh.android.Utilities.Dialog.SafFileSelectDialogFragment.java

private void initViewWidget() {
    if (mDebugEnable)
        Log.v(APPLICATION_TAG, "initViewWidget");

    if (mDebugEnable)
        Log.v(APPLICATION_TAG, "Create=" + mDialogEnableCreate + ", Title=" + mDialogTitle + ", lurl="
                + mDialogLocalUuid + ", ldir=" + mDialogLocalDir + ", file name=" + mDialogFileName);

    mThemeColorList = ThemeUtil.getThemeColorList(getActivity());

    mDialog.setContentView(R.layout.file_select_edit_dlg);
    LinearLayout title_view = (LinearLayout) mDialog.findViewById(R.id.file_select_edit_dlg_title_view);
    title_view.setBackgroundColor(mThemeColorList.dialog_title_background_color);
    TextView title = (TextView) mDialog.findViewById(R.id.file_select_edit_dlg_title);
    title.setTextColor(mThemeColorList.text_color_dialog_title);
    title.setText(mDialogTitle);/* www .jav a  2s. c  o  m*/
    final TextView dlg_msg = (TextView) mDialog.findViewById(R.id.file_select_edit_dlg_msg);
    final Button btnHome = (Button) mDialog.findViewById(R.id.file_select_edit_dlg_home_dir_btn);
    btnHome.setTextColor(mThemeColorList.text_color_primary);
    btnHome.setVisibility(Button.VISIBLE);

    final Button btnCreate = (Button) mDialog.findViewById(R.id.file_select_edit_dlg_create_btn);
    btnCreate.setTextColor(mThemeColorList.text_color_primary);
    final Button btnOk = (Button) mDialog.findViewById(R.id.file_select_edit_dlg_ok_btn);
    //      btnOk.setTextColor(mThemeColorList.text_color_primary);
    final Button btnCancel = (Button) mDialog.findViewById(R.id.file_select_edit_dlg_cancel_btn);
    btnCancel.setTextColor(mThemeColorList.text_color_primary);
    final Button btnRefresh = (Button) mDialog.findViewById(R.id.file_select_edit_dlg_refresh_btn);
    btnRefresh.setTextColor(mThemeColorList.text_color_primary);

    LinearLayout ll_dlg_view = (LinearLayout) mDialog.findViewById(R.id.file_select_edit_dlg_view);
    //      LinearLayout ll_dlg_view_filename=(LinearLayout) mDialog.findViewById(R.id.file_select_edit_dlg_view_filename);
    //      LinearLayout ll_dlg_view_create=(LinearLayout) mDialog.findViewById(R.id.file_select_edit_dlg_view_create);
    //      LinearLayout ll_dlg_view_btn=(LinearLayout) mDialog.findViewById(R.id.file_select_edit_dlg_view_btn);
    ll_dlg_view.setBackgroundColor(mThemeColorList.dialog_msg_background_color);
    //      ll_dlg_view_filename.setBackgroundColor(mThemeColorList.dialog_msg_background_color);
    //      ll_dlg_view_create.setBackgroundColor(mThemeColorList.dialog_msg_background_color);
    //      ll_dlg_view_btn.setBackgroundColor(mThemeColorList.dialog_msg_background_color);

    final Activity activity = getActivity();
    final Context context = activity.getApplicationContext();

    if (mDialogEnableCreate) {
        btnCreate.setVisibility(TextView.VISIBLE);
    }

    LinearLayout ll_mp = (LinearLayout) mDialog.findViewById(R.id.file_select_edit_dlg_mp_view);
    ll_mp.setVisibility(LinearLayout.GONE);

    mTreeFileListView = (ListView) mDialog.findViewById(android.R.id.list);
    final EditText filename = (EditText) mDialog.findViewById(R.id.file_select_edit_dlg_file_name);
    final CustomTextView dir_name = (CustomTextView) mDialog.findViewById(R.id.file_select_edit_dlg_dir_name);
    filename.setOnKeyListener(new OnKeyListener() {
        @Override
        public boolean onKey(View arg0, int keyCode, KeyEvent event) {
            if (//event.getAction() == KeyEvent.ACTION_DOWN &&
            keyCode == KeyEvent.KEYCODE_ENTER) {
                return true;
            }
            return false;
        }
    });
    if (!mDialogSingleSelect) {
        filename.setVisibility(EditText.GONE);
    }
    //    if (dirs.size()<=2)   v_spacer.setVisibility(TextView.VISIBLE);

    mTreeFilelistAdapter = new TreeFilelistAdapter(activity, mDialogSingleSelect, true);
    mTreeFileListView.setAdapter(mTreeFilelistAdapter);
    //       if (mDialogFileOnly) {
    //          mTreeFilelistAdapter.setDirectorySelectable(false);
    //          mTreeFilelistAdapter.setFileSelectable(true);
    //       }
    //       if (mDialogDirOnly) {
    //          mTreeFilelistAdapter.setDirectorySelectable(true);
    //          mTreeFilelistAdapter.setFileSelectable(false);
    //       }

    ArrayList<TreeFilelistItem> tfl = createLocalFilelist(mDialogFileOnly, mDialogLocalUuid, "");
    if (tfl.size() == 0) {
        tfl.add(new TreeFilelistItem(context.getString(R.string.msgs_file_select_edit_dir_empty)));
    } else {
        mTreeFilelistAdapter.setDataList(tfl);
        if (!mDialogLocalDir.equals("")) {
            String sel_dir = mDialogLocalDir;
            String n_dir = "", e_dir = "";
            if (sel_dir.startsWith("/"))
                n_dir = sel_dir.substring(1);
            else
                n_dir = sel_dir;
            if (n_dir.endsWith("/"))
                e_dir = n_dir.substring(0, n_dir.length() - 1);
            else
                e_dir = n_dir;
            selectLocalDirTree(e_dir);
        }
        if (!mDialogFileName.equals(""))
            selectLocalDirTreeFile(mDialogFileName);
    }
    mTreeFileListView.setScrollingCacheEnabled(false);
    mTreeFileListView.setScrollbarFadingEnabled(false);

    if (mSavedViewContentsValue != null && mSavedViewContentsValue.mainDialogFilename != null) {
        filename.setText(mSavedViewContentsValue.mainDialogFilename);
        filename.setSelection(mSavedViewContentsValue.mainDialogFilenameSelStart,
                mSavedViewContentsValue.mainDialogFilenameTextSelEnd);
        dir_name.setText(mSavedViewContentsValue.mainDialogDirName);
    } else {
        //          if (mDialogLocalDir.equals("")) filename.setText(mDialogLocalUuid+mDialogFileName);
        //          else filename.setText(mDialogLocalUuid+mDialogLocalDir+"/"+mDialogFileName);
        //         filename.setSelection(filename.getText().toString().length());
        dir_name.setText(mDialogLocalDir + "/");
        filename.setText(mDialogFileName);
    }

    //      CommonDialog.setDlgBoxSizeLimit(mDialog,true);
    //   setDlgBoxSize(dialog,0,0,false);

    if (!mDialogSingleSelect)
        btnOk.setEnabled(false);

    NotifyEvent cb_ntfy = new NotifyEvent(context);
    // set file list thread response listener 
    cb_ntfy.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            int p = (Integer) o[0];
            boolean p_chk = (Boolean) o[1];
            if (mDialogSingleSelect) {
                if (mTreeFilelistAdapter.getDataItem(p).isChecked() && !p_chk) {
                    if (p != -1) {
                        if (mTreeFilelistAdapter.getDataItem(p).isChecked()) {
                            if (mTreeFilelistAdapter.getDataItem(p).isDir()) {
                                dir_name.setText(mTreeFilelistAdapter.getDataItem(p).getPath()
                                        + mTreeFilelistAdapter.getDataItem(p).getName() + "/");
                                //                           filename.setText("");
                            } else {
                                dir_name.setText(mTreeFilelistAdapter.getDataItem(p).getPath());
                                filename.setText(mTreeFilelistAdapter.getDataItem(p).getName());
                            }
                        }
                    }
                }
                if (mDialogFileOnly) {
                    if (filename.getText().length() > 0) {
                        btnOk.setEnabled(true);
                        putDlgMsg(dlg_msg, "");
                    } else {
                        btnOk.setEnabled(false);
                        putDlgMsg(dlg_msg,
                                context.getString(R.string.msgs_file_select_edit_dlg_filename_not_specified));
                    }
                } else {
                    if (mTreeFilelistAdapter.isDataItemIsSelected() || filename.getText().length() > 0) {
                        btnOk.setEnabled(true);
                        putDlgMsg(dlg_msg, "");
                    } else {
                        putDlgMsg(dlg_msg,
                                context.getString(R.string.msgs_file_select_edit_dlg_directory_not_selected));
                        btnOk.setEnabled(false);
                    }
                }
            } else {
                if (mTreeFilelistAdapter.getDataItem(p).isDir()) {
                    dir_name.setText(mTreeFilelistAdapter.getDataItem(p).getPath()
                            + mTreeFilelistAdapter.getDataItem(p).getName() + "/");
                } else {
                    dir_name.setText(mTreeFilelistAdapter.getDataItem(p).getPath());
                    filename.setText(mTreeFilelistAdapter.getDataItem(p).getName());
                }
                putDlgMsg(dlg_msg, "");
                btnOk.setEnabled(true);
            }
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
            boolean checked = false;
            //         int p=(Integer) o[0];
            boolean p_chk = (Boolean) o[1];
            if (mDialogSingleSelect) {
                if (p_chk) {
                    for (int i = 0; i < mTreeFilelistAdapter.getDataItemCount(); i++) {
                        if (mTreeFilelistAdapter.getDataItem(i).isChecked()) {
                            checked = true;
                            break;
                        }
                    }
                    if (checked)
                        btnOk.setEnabled(true);
                    else
                        btnOk.setEnabled(false);
                }
            } else {
                //               Log.v("","sel="+p_chk);
                btnOk.setEnabled(false);
                for (int i = 0; i < mTreeFilelistAdapter.getDataItemCount(); i++) {
                    if (mTreeFilelistAdapter.getDataItem(i).isChecked()) {
                        btnOk.setEnabled(true);
                        break;
                    }
                }
            }
        }
    });
    mTreeFilelistAdapter.setCbCheckListener(cb_ntfy);

    //      if (mDialogLocalUuid.equals(filename.getText().toString())) btnOk.setEnabled(false);
    filename.addTextChangedListener(new TextWatcher() {
        @Override
        public void afterTextChanged(Editable s) {
            if (mDialogSingleSelect) {
                if (s.length() != 0) {
                    btnOk.setEnabled(true);
                    putDlgMsg(dlg_msg, "");
                } else {
                    btnOk.setEnabled(false);
                    putDlgMsg(dlg_msg,
                            context.getString(R.string.msgs_file_select_edit_dlg_filename_not_specified));
                }
            }
        }

        @Override
        public void beforeTextChanged(CharSequence s, int start, int count, int after) {
        }

        @Override
        public void onTextChanged(CharSequence s, int start, int before, int count) {
        }
    });

    NotifyEvent ntfy_expand_close = new NotifyEvent(context);
    ntfy_expand_close.setListener(new NotifyEventListener() {
        @Override
        public void positiveResponse(Context c, Object[] o) {
            int idx = (Integer) o[0];
            final int pos = mTreeFilelistAdapter.getItem(idx);
            final TreeFilelistItem tfi = mTreeFilelistAdapter.getDataItem(pos);
            if (tfi.getName().startsWith("---"))
                return;
            if (tfi.isDir())
                processLocalDirTree(mDialogFileOnly, mDialogLocalUuid, pos, tfi, mTreeFilelistAdapter);
            else {
                mTreeFilelistAdapter.setDataItemIsSelected(pos);
                dir_name.setText(mTreeFilelistAdapter.getDataItem(pos).getPath());
                filename.setText(mTreeFilelistAdapter.getDataItem(pos).getName());
                if (mTreeFilelistAdapter.getDataItem(pos).isDir() && mDialogFileOnly)
                    btnOk.setEnabled(false);
                else
                    btnOk.setEnabled(true);
            }
        }

        @Override
        public void negativeResponse(Context c, Object[] o) {
        }
    });
    mTreeFilelistAdapter.setExpandCloseListener(ntfy_expand_close);
    mTreeFileListView.setOnItemClickListener(new OnItemClickListener() {
        public void onItemClick(AdapterView<?> items, View view, int idx, long id) {
            final int pos = mTreeFilelistAdapter.getItem(idx);
            final TreeFilelistItem tfi = mTreeFilelistAdapter.getDataItem(pos);
            if (tfi.getName().startsWith("---"))
                return;
            if (tfi.isDir())
                processLocalDirTree(mDialogFileOnly, mDialogLocalUuid, pos, tfi, mTreeFilelistAdapter);
            else {
                mTreeFilelistAdapter.setDataItemIsSelected(pos);
                dir_name.setText(mTreeFilelistAdapter.getDataItem(pos).getPath());
                filename.setText(mTreeFilelistAdapter.getDataItem(pos).getName());
                if (mTreeFilelistAdapter.getDataItem(pos).isDir() && mDialogFileOnly)
                    btnOk.setEnabled(false);
                else
                    btnOk.setEnabled(true);
            }
        }
    });

    mTreeFileListView.setOnItemLongClickListener(new OnItemLongClickListener() {
        @Override
        public boolean onItemLongClick(AdapterView<?> arg0, View arg1, final int position, long arg3) {
            return true;
        }
    });

    btnHome.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            dir_name.setText("/");
        }
    });

    //Create button
    btnCreate.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            NotifyEvent ntfy = new NotifyEvent(context);
            // set file list thread response listener 
            ntfy.setListener(new NotifyEventListener() {
                @Override
                public void positiveResponse(Context c, Object[] o) {
                    //                  btnRefresh.performClick();                  
                }

                @Override
                public void negativeResponse(Context c, Object[] o) {
                }

            });
            //            String mp="";
            //            for(TreeFilelistItem tfi:mTreeFilelistAdapter.getDataList()) {
            //               if (tfi.isChecked()) {
            //                  mp=tfi.getPath()+tfi.getName();
            //                  break;
            //               }
            //            }
            fileSelectEditDialogCreateBtn(activity, context,
                    dir_name.getText().substring(0, dir_name.getText().length() - 1), "", mTreeFilelistAdapter,
                    ntfy, mTreeFileListView);

        }
    });
    //Refresh button
    btnRefresh.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            ArrayList<TreeFilelistItem> tfl = createLocalFilelist(mDialogFileOnly, mDialogLocalUuid, "");//mDialogLocalUuid,"");
            if (tfl.size() < 1)
                tfl.add(new TreeFilelistItem(context.getString(R.string.msgs_file_select_edit_dir_empty)));
            mTreeFilelistAdapter.setDataList(tfl);
        }
    });
    //OK button
    //      btnOk.setEnabled(false);
    btnOk.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            if (mDialogSingleSelect) {
                String[] sl_array = new String[] {
                        dir_name.getText().toString() + filename.getText().toString() };
                if (mNotifyEvent != null)
                    mNotifyEvent.notifyToListener(true, sl_array);
            } else {
                ArrayList<String> sl = new ArrayList<String>();
                ArrayList<TreeFilelistItem> tfl = mTreeFilelistAdapter.getDataList();
                for (TreeFilelistItem li : tfl) {
                    if (li.isChecked()) {
                        if (li.isDir())
                            sl.add(li.getPath() + li.getName());
                        else
                            sl.add(li.getPath() + li.getName());
                    }
                }
                String[] sl_array = new String[sl.size()];
                for (int i = 0; i < sl.size(); i++) {
                    if (mDialogSelectedFilePathWithMountPoint)
                        sl_array[i] = sl.get(i);
                    else
                        sl_array[i] = sl.get(i);
                    //                  Log.v("","sel="+sl_array[i]);
                }
                if (mNotifyEvent != null)
                    mNotifyEvent.notifyToListener(true, sl_array);
            }
            //            mDialog.dismiss();
            mFragment.dismiss();
        }
    });
    // CANCEL?
    btnCancel.setOnClickListener(new View.OnClickListener() {
        public void onClick(View v) {
            //            mDialog.dismiss();
            mFragment.dismiss();
            if (mNotifyEvent != null)
                mNotifyEvent.notifyToListener(false, null);
        }
    });

}

From source file:com.android.mail.compose.ComposeActivity.java

@Override
protected final void onRestoreInstanceState(Bundle savedInstanceState) {
    final boolean hasAccounts = mAccounts != null && mAccounts.length > 0;
    if (hasAccounts) {
        clearChangeListeners();/*from w ww  .  j  av a2  s .c  o m*/
    }
    super.onRestoreInstanceState(savedInstanceState);
    if (mInnerSavedState != null) {
        if (mInnerSavedState.containsKey(EXTRA_FOCUS_SELECTION_START)) {
            int selectionStart = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_START);
            int selectionEnd = mInnerSavedState.getInt(EXTRA_FOCUS_SELECTION_END);
            // There should be a focus and it should be an EditText since we
            // only save these extras if these conditions are true.
            EditText focusEditText = (EditText) getCurrentFocus();
            final int length = focusEditText.getText().length();
            if (selectionStart < length && selectionEnd < length) {
                focusEditText.setSelection(selectionStart, selectionEnd);
            }
        }
    }
    if (hasAccounts) {
        initChangeListeners();
    }
}