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 index) 

Source Link

Document

Convenience for Selection#setSelection(Spannable,int) .

Usage

From source file:com.money.manager.ex.common.CategoryListFragment.java

/**
 * Show alter binaryDialog, for create or edit new category
 *//*  w  ww .  j  a  v  a  2  s.  c om*/
private void showDialogEditCategoryName(final SQLTypeTransaction type, final int categoryId,
        final CharSequence categoryName) {
    // inflate view
    View viewDialog = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_new_edit_category, null);

    final EditText edtCategName = (EditText) viewDialog.findViewById(R.id.editTextCategName);
    // set category description
    edtCategName.setText(categoryName);
    if (!TextUtils.isEmpty(categoryName)) {
        edtCategName.setSelection(categoryName.length());
    }

    int titleId = type.equals(SQLTypeTransaction.INSERT) ? R.string.add_category : R.string.edit_categoryName;

    new MaterialDialog.Builder(getContext()).customView(viewDialog, true)
            .icon(FontIconDrawable.inflate(getContext(), R.xml.ic_tag)).title(titleId)
            .positiveText(android.R.string.ok).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    // get category description
                    String name = edtCategName.getText().toString();
                    CategoryService service = new CategoryService(getActivity());

                    switch (type) {
                    case INSERT:
                        int insertResult = service.createNew(name);

                        if (insertResult <= 0) {
                            Toast.makeText(getActivity(), R.string.db_insert_failed, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case UPDATE:
                        int updateResult = service.update(categoryId, name);
                        if (updateResult <= 0) {
                            Toast.makeText(getActivity(), R.string.db_update_failed, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
                    // restart loader
                    restartLoader();
                }
            }).negativeText(android.R.string.cancel).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    dialog.cancel();
                }
            }).build().show();
}

From source file:org.liberty.android.fantastischmemo.ui.CardEditor.java

private void addTextToView(EditText v, String text) {
    String origText = v.getText().toString();
    /*//w  w w .  j  av a  2  s  .  c o m
     * keep track of the cursor location and restore it
     * after pasting because the default location is the
     * begining of the EditText
     */
    int cursorPos = v.getSelectionStart();
    try {
        String newText = origText.substring(0, cursorPos) + text
                + origText.substring(cursorPos, origText.length());

        v.setText(newText);
        v.setSelection(cursorPos + text.length());

    } catch (Exception e) {
        Log.e(TAG, "cursor position is wrong", e);
    }
}

From source file:com.ericsun.duom.Framework.Activity.BaseActivity.java

public void setPricePoint(final EditText editText) {
    editText.addTextChangedListener(new TextWatcher() {

        @Override//from w  w  w. j a  va2 s  . com
        public void onTextChanged(CharSequence s, int start, int before, int count) {
            if (s.toString().contains(".")) {
                if (s.length() - 1 - s.toString().indexOf(".") > 2) {
                    s = s.toString().subSequence(0, s.toString().indexOf(".") + 3);
                    editText.setText(s);
                    editText.setSelection(s.length());
                }
            }
            if (s.toString().trim().substring(0).equals(".")) {
                s = "";
            }

            if (s.toString().startsWith("0") && s.toString().trim().length() > 1) {
                if (!s.toString().substring(1, 2).equals(".")) {
                    editText.setText(s.subSequence(0, 1));
                    editText.setSelection(1);
                    return;
                }
            }
        }

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

        }

        @Override
        public void afterTextChanged(Editable editable) {
            // TODO Auto-generated method stub
        }

    });

}

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

/**
 * On activity result//  ww w . java2 s  .  c o m
 */
@Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
    if (resultCode != RESULT_OK) {
        // ignore other result codes
        return;
    }

    switch (requestCode) {
    case REQUEST_CODE_SPEECH:
        ArrayList<String> matches = data.getStringArrayListExtra(RecognizerIntent.EXTRA_RESULTS);
        if (matches.size() > 0) {
            ((EditText) findViewById(R.id.input)).setText(matches.get(0));
        }
        break;
    case REQUEST_CODE_JOIN:
        joinChannelBuffer = data.getExtras().getString("channel");
        break;
    case REQUEST_CODE_USERS:
        Intent intent = new Intent(this, UserActivity.class);
        intent.putExtra(Extra.USER, data.getStringExtra(Extra.USER));
        startActivityForResult(intent, REQUEST_CODE_USER);
        break;
    case REQUEST_CODE_NICK_COMPLETION:
        insertNickCompletion((EditText) findViewById(R.id.input), data.getExtras().getString(Extra.USER));
        break;
    case REQUEST_CODE_USER:
        final int actionId = data.getExtras().getInt(Extra.ACTION);
        final String nickname = data.getExtras().getString(Extra.USER);
        final IRCConnection connection = binder.getService().getConnection(server.getId());
        final String conversation = server.getSelectedConversation();
        final Handler handler = new Handler();

        // XXX: Implement me - The action should be handled after onResume()
        //                     to catch the broadcasts... now we just wait a second
        // Yes .. that's very ugly - we need some kind of queue that is handled after onResume()

        new Thread() {
            @Override
            public void run() {
                try {
                    Thread.sleep(1000);
                } catch (InterruptedException e) {
                    // Do nothing
                }

                String nicknameWithoutPrefix = nickname;

                while (nicknameWithoutPrefix.startsWith("@") || nicknameWithoutPrefix.startsWith("+")
                        || nicknameWithoutPrefix.startsWith(".") || nicknameWithoutPrefix.startsWith("%")) {
                    // Strip prefix(es) now
                    nicknameWithoutPrefix = nicknameWithoutPrefix.substring(1);
                }

                switch (actionId) {
                case User.ACTION_REPLY:
                    final String replyText = nicknameWithoutPrefix + ": ";
                    handler.post(new Runnable() {
                        @Override
                        public void run() {
                            EditText input = (EditText) findViewById(R.id.input);
                            input.setText(replyText);
                            input.setSelection(replyText.length());
                        }
                    });
                    break;
                case User.ACTION_QUERY:
                    Conversation query = server.getConversation(nicknameWithoutPrefix);
                    if (query == null) {
                        // Open a query if there's none yet
                        query = new Query(nicknameWithoutPrefix);
                        query.setHistorySize(binder.getService().getSettings().getHistorySize());
                        server.addConversation(query);

                        Intent intent = Broadcast.createConversationIntent(Broadcast.CONVERSATION_NEW,
                                server.getId(), nicknameWithoutPrefix);
                        binder.getService().sendBroadcast(intent);
                    }
                    break;
                case User.ACTION_OP:
                    connection.op(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEOP:
                    connection.deOp(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_VOICE:
                    connection.voice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_DEVOICE:
                    connection.deVoice(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_KICK:
                    connection.kick(conversation, nicknameWithoutPrefix);
                    break;
                case User.ACTION_BAN:
                    connection.ban(conversation, nicknameWithoutPrefix + "!*@*");
                    break;
                }
            }
        }.start();

        break;
    }
}

From source file:com.money.manager.ex.common.CategoryListFragment.java

/**
 * Show alter binaryDialog, for create or edit new category
 *///from  w ww.jav a2  s.c om
private void showDialogEditSubCategoryName(final SQLTypeTransaction type, final int categoryId,
        final int subCategoryId, final CharSequence subCategName) {

    // inflate view
    View viewDialog = LayoutInflater.from(getActivity()).inflate(R.layout.dialog_new_edit_subcategory, null);

    final EditText edtSubCategName = (EditText) viewDialog.findViewById(R.id.editTextCategName);
    final Spinner spnCategory = (Spinner) viewDialog.findViewById(R.id.spinnerCategory);
    // set category description
    edtSubCategName.setText(subCategName);
    if (!TextUtils.isEmpty(subCategName)) {
        edtSubCategName.setSelection(subCategName.length());
    }

    // Fill categories list.
    CategoryService categoryService = new CategoryService(getActivity());
    final List<Category> categories = categoryService.getList();

    ArrayList<String> categoryNames = new ArrayList<>();
    ArrayList<Integer> categoryIds = new ArrayList<>();
    for (Category category : categories) {
        categoryIds.add(category.getId());
        categoryNames.add(category.getName().toString());
    }
    ArrayAdapter<String> adapterCategory = new ArrayAdapter<>(getActivity(),
            android.R.layout.simple_spinner_item, categoryNames);
    adapterCategory.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
    spnCategory.setAdapter(adapterCategory);
    //select category if present
    if (categoryId > 0) {
        spnCategory.setSelection(categoryIds.indexOf(categoryId), true);
    }

    int titleId = type.equals(SQLTypeTransaction.INSERT) ? R.string.add_subcategory
            : R.string.edit_categoryName;

    new MaterialDialog.Builder(getContext()).customView(viewDialog, true)
            .icon(FontIconDrawable.inflate(getContext(), R.xml.ic_tag)).title(titleId)
            .positiveText(android.R.string.ok).onPositive(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    // get category description
                    String name = edtSubCategName.getText().toString();
                    // check position
                    if (spnCategory.getSelectedItemPosition() == Spinner.INVALID_POSITION)
                        return;
                    // get category id
                    int categId = categories.get(spnCategory.getSelectedItemPosition()).getId();
                    ContentValues values = new ContentValues();
                    values.put(Subcategory.CATEGID, categId);
                    values.put(Subcategory.SUBCATEGNAME, name);

                    SubcategoryRepository repo = new SubcategoryRepository(getActivity());

                    // check type transaction is request
                    switch (type) {
                    case INSERT:
                        if (getActivity().getContentResolver().insert(repo.getUri(), values) == null) {
                            Toast.makeText(getActivity(), R.string.db_insert_failed, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    case UPDATE:
                        if (getActivity().getContentResolver().update(repo.getUri(), values, Subcategory.CATEGID
                                + "=" + categoryId + " AND " + Subcategory.SUBCATEGID + "=" + subCategoryId,
                                null) == 0) {
                            Toast.makeText(getActivity(), R.string.db_update_failed, Toast.LENGTH_SHORT).show();
                        }
                        break;
                    }
                    // restart loader
                    restartLoader();
                }
            }).negativeText(android.R.string.cancel).onNegative(new MaterialDialog.SingleButtonCallback() {
                @Override
                public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
                    dialog.cancel();
                }
            }).build().show();
}

From source file:com.farmerbb.taskbar.service.StartMenuService.java

@SuppressLint("RtlHardcoded")
private void drawStartMenu() {
    IconCache.getInstance(this).clearCache();

    final SharedPreferences pref = U.getSharedPreferences(this);
    final boolean hasHardwareKeyboard = getResources()
            .getConfiguration().keyboard != Configuration.KEYBOARD_NOKEYS;

    switch (pref.getString("show_search_bar", "keyboard")) {
    case "always":
        shouldShowSearchBox = true;/*from  w w  w .  j a  va  2 s. c  o m*/
        break;
    case "keyboard":
        shouldShowSearchBox = hasHardwareKeyboard;
        break;
    case "never":
        shouldShowSearchBox = false;
        break;
    }

    // Initialize layout params
    windowManager = (WindowManager) getSystemService(WINDOW_SERVICE);
    U.setCachedRotation(windowManager.getDefaultDisplay().getRotation());

    final WindowManager.LayoutParams params = new WindowManager.LayoutParams(
            WindowManager.LayoutParams.WRAP_CONTENT, WindowManager.LayoutParams.WRAP_CONTENT,
            WindowManager.LayoutParams.TYPE_PHONE,
            shouldShowSearchBox ? 0
                    : WindowManager.LayoutParams.FLAG_NOT_FOCUSABLE
                            | WindowManager.LayoutParams.FLAG_ALT_FOCUSABLE_IM,
            PixelFormat.TRANSLUCENT);

    // Determine where to show the start menu on screen
    switch (U.getTaskbarPosition(this)) {
    case "bottom_left":
        layoutId = R.layout.start_menu_left;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        break;
    case "bottom_vertical_left":
        layoutId = R.layout.start_menu_vertical_left;
        params.gravity = Gravity.BOTTOM | Gravity.LEFT;
        break;
    case "bottom_right":
        layoutId = R.layout.start_menu_right;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        break;
    case "bottom_vertical_right":
        layoutId = R.layout.start_menu_vertical_right;
        params.gravity = Gravity.BOTTOM | Gravity.RIGHT;
        break;
    case "top_left":
        layoutId = R.layout.start_menu_top_left;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        break;
    case "top_vertical_left":
        layoutId = R.layout.start_menu_vertical_left;
        params.gravity = Gravity.TOP | Gravity.LEFT;
        break;
    case "top_right":
        layoutId = R.layout.start_menu_top_right;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        break;
    case "top_vertical_right":
        layoutId = R.layout.start_menu_vertical_right;
        params.gravity = Gravity.TOP | Gravity.RIGHT;
        break;
    }

    // Initialize views
    int theme = 0;

    switch (pref.getString("theme", "light")) {
    case "light":
        theme = R.style.AppTheme;
        break;
    case "dark":
        theme = R.style.AppTheme_Dark;
        break;
    }

    ContextThemeWrapper wrapper = new ContextThemeWrapper(this, theme);
    layout = (StartMenuLayout) LayoutInflater.from(wrapper).inflate(layoutId, null);
    startMenu = (GridView) layout.findViewById(R.id.start_menu);

    if ((shouldShowSearchBox && !hasHardwareKeyboard)
            || Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1)
        layout.viewHandlesBackButton();

    boolean scrollbar = pref.getBoolean("scrollbar", false);
    startMenu.setFastScrollEnabled(scrollbar);
    startMenu.setFastScrollAlwaysVisible(scrollbar);
    startMenu.setScrollBarStyle(scrollbar ? View.SCROLLBARS_OUTSIDE_INSET : View.SCROLLBARS_INSIDE_OVERLAY);

    if (pref.getBoolean("transparent_start_menu", false))
        startMenu.setBackgroundColor(0);

    searchView = (SearchView) layout.findViewById(R.id.search);

    int backgroundTint = U.getBackgroundTint(this);

    FrameLayout startMenuFrame = (FrameLayout) layout.findViewById(R.id.start_menu_frame);
    FrameLayout searchViewLayout = (FrameLayout) layout.findViewById(R.id.search_view_layout);
    startMenuFrame.setBackgroundColor(backgroundTint);
    searchViewLayout.setBackgroundColor(backgroundTint);

    if (shouldShowSearchBox) {
        if (!hasHardwareKeyboard)
            searchView.setIconifiedByDefault(true);

        searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
            @Override
            public boolean onQueryTextSubmit(String query) {
                if (!hasSubmittedQuery) {
                    ListAdapter adapter = startMenu.getAdapter();
                    if (adapter != null) {
                        hasSubmittedQuery = true;

                        if (adapter.getCount() > 0) {
                            View view = adapter.getView(0, null, startMenu);
                            LinearLayout layout = (LinearLayout) view.findViewById(R.id.entry);
                            layout.performClick();
                        } else {
                            if (pref.getBoolean("hide_taskbar", true)
                                    && !FreeformHackHelper.getInstance().isInFreeformWorkspace())
                                LocalBroadcastManager.getInstance(StartMenuService.this)
                                        .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_TASKBAR"));
                            else
                                LocalBroadcastManager.getInstance(StartMenuService.this)
                                        .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));

                            Intent intent = new Intent(Intent.ACTION_WEB_SEARCH);
                            intent.putExtra(SearchManager.QUERY, query);
                            intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                            if (intent.resolveActivity(getPackageManager()) != null)
                                startActivity(intent);
                            else {
                                Uri uri = new Uri.Builder().scheme("https").authority("www.google.com")
                                        .path("search").appendQueryParameter("q", query).build();

                                intent = new Intent(Intent.ACTION_VIEW);
                                intent.setData(uri);
                                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);

                                try {
                                    startActivity(intent);
                                } catch (ActivityNotFoundException e) {
                                    /* Gracefully fail */ }
                            }
                        }
                    }
                }
                return true;
            }

            @Override
            public boolean onQueryTextChange(String newText) {
                searchView.setIconified(false);

                View closeButton = searchView.findViewById(R.id.search_close_btn);
                if (closeButton != null)
                    closeButton.setVisibility(View.GONE);

                refreshApps(newText, false);

                if (Build.VERSION.SDK_INT < Build.VERSION_CODES.LOLLIPOP_MR1) {
                    new Handler().postDelayed(() -> {
                        EditText editText = (EditText) searchView.findViewById(R.id.search_src_text);
                        if (editText != null) {
                            editText.requestFocus();
                            editText.setSelection(editText.getText().length());
                        }
                    }, 50);
                }

                return true;
            }
        });

        searchView.setOnQueryTextFocusChangeListener((view, b) -> {
            if (!hasHardwareKeyboard) {
                ViewGroup.LayoutParams params1 = startMenu.getLayoutParams();
                params1.height = getResources().getDimensionPixelSize(b
                        && !U.isServiceRunning(this, "com.farmerbb.secondscreen.service.DisableKeyboardService")
                                ? R.dimen.start_menu_height_half
                                : R.dimen.start_menu_height);
                startMenu.setLayoutParams(params1);
            }

            if (!b) {
                if (hasHardwareKeyboard && Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP_MR1)
                    LocalBroadcastManager.getInstance(StartMenuService.this)
                            .sendBroadcast(new Intent("com.farmerbb.taskbar.HIDE_START_MENU"));
                else {
                    InputMethodManager imm = (InputMethodManager) getSystemService(INPUT_METHOD_SERVICE);
                    imm.hideSoftInputFromWindow(view.getWindowToken(), 0);
                }
            }
        });

        searchView.setImeOptions(EditorInfo.IME_ACTION_DONE | EditorInfo.IME_FLAG_NO_EXTRACT_UI);

        LinearLayout powerButton = (LinearLayout) layout.findViewById(R.id.power_button);
        powerButton.setOnClickListener(view -> {
            int[] location = new int[2];
            view.getLocationOnScreen(location);
            openContextMenu(location);
        });

        powerButton.setOnGenericMotionListener((view, motionEvent) -> {
            if (motionEvent.getAction() == MotionEvent.ACTION_BUTTON_PRESS
                    && motionEvent.getButtonState() == MotionEvent.BUTTON_SECONDARY) {
                int[] location = new int[2];
                view.getLocationOnScreen(location);
                openContextMenu(location);
            }
            return false;
        });

        searchViewLayout.setOnClickListener(view -> searchView.setIconified(false));

        startMenu.setOnItemClickListener((parent, view, position, id) -> {
            hideStartMenu();

            AppEntry entry = (AppEntry) parent.getAdapter().getItem(position);
            U.launchApp(StartMenuService.this, entry.getPackageName(), entry.getComponentName(),
                    entry.getUserId(StartMenuService.this), null, false, false);
        });

        if (pref.getBoolean("transparent_start_menu", false))
            layout.findViewById(R.id.search_view_child_layout).setBackgroundColor(0);
    } else
        searchViewLayout.setVisibility(View.GONE);

    textView = (TextView) layout.findViewById(R.id.no_apps_found);

    LocalBroadcastManager.getInstance(this).unregisterReceiver(toggleReceiver);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(toggleReceiverAlt);
    LocalBroadcastManager.getInstance(this).unregisterReceiver(hideReceiver);

    LocalBroadcastManager.getInstance(this).registerReceiver(toggleReceiver,
            new IntentFilter("com.farmerbb.taskbar.TOGGLE_START_MENU"));
    LocalBroadcastManager.getInstance(this).registerReceiver(toggleReceiverAlt,
            new IntentFilter("com.farmerbb.taskbar.TOGGLE_START_MENU_ALT"));
    LocalBroadcastManager.getInstance(this).registerReceiver(hideReceiver,
            new IntentFilter("com.farmerbb.taskbar.HIDE_START_MENU"));

    handler = new Handler();
    refreshApps(true);

    windowManager.addView(layout, params);
}

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

/**
 * Insert a given nick completion into the input line
 *
 * @param input The input line widget, with the incomplete nick selected
 * @param nick The completed nick// w  ww. ja va  2s. c  o m
 */
private void insertNickCompletion(EditText input, String nick) {
    int start = input.getSelectionStart();
    int end = input.getSelectionEnd();
    nick = removeStatusChar(nick);

    if (start == 0) {
        nick += ":";
    }

    nick += " ";
    input.getText().replace(start, end, nick, 0, nick.length());
    // put cursor after inserted text
    input.setSelection(start + nick.length());
    input.clearComposingText();
    input.post(new Runnable() {
        @Override
        public void run() {
            // make the softkeyboard come up again (only if no hw keyboard is attached)
            EditText input = (EditText) findViewById(R.id.input);
            openSoftKeyboard(input);
        }
    });

    input.requestFocus();
}

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

/**
 * Insert a given nick completion into the input line
 *
 * @param input The input line widget, with the incomplete nick selected
 * @param nick The completed nick//from ww  w  . j  a  va  2s .  c o  m
 */
private void insertNickCompletion(final EditText input, String nick) {
    int start = input.getSelectionStart();
    int end = input.getSelectionEnd();
    nick = removeStatusChar(nick);

    if (start == 0) {
        nick += ":";
    }

    nick += " ";
    input.getText().replace(start, end, nick, 0, nick.length());
    // put cursor after inserted text
    input.setSelection(start + nick.length());
    input.clearComposingText();
    input.post(new Runnable() {
        @Override
        public void run() {
            // make the softkeyboard come up again (only if no hw keyboard is attached)
            openSoftKeyboard(input);
        }
    });

    input.requestFocus();
}

From source file:de.baumann.hhsmoodle.data_schedule.Schedule_Fragment.java

private void setScheduleList() {

    final int line = sharedPref.getInt("getLine", 1);
    //display data
    final int layoutstyle = R.layout.list_item_schedule;
    int[] xml_id = new int[] { R.id.textView_title_notes, R.id.textView_des_notes, R.id.att_notes,
            R.id.textView_create_notes };
    String[] column = new String[] { "schedule_title", "schedule_content", "schedule_attachment",
            "schedule_creation" };
    final Cursor row = db.fetchAllData();
    adapter = new SimpleCursorAdapter(getActivity(), layoutstyle, row, column, xml_id, 0) {
        @Override//  w  ww  . ja  v  a  2  s.  c om
        public View getView(final int position, View convertView, ViewGroup parent) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String schedule_title = row2.getString(row2.getColumnIndexOrThrow("schedule_title"));
            final String schedule_content = row2.getString(row2.getColumnIndexOrThrow("schedule_content"));
            final String schedule_icon = row2.getString(row2.getColumnIndexOrThrow("schedule_icon"));
            final String schedule_attachment = row2
                    .getString(row2.getColumnIndexOrThrow("schedule_attachment"));
            final String schedule_creation = row2.getString(row2.getColumnIndexOrThrow("schedule_creation"));
            final String schedule_id = row2.getString(row2.getColumnIndexOrThrow("schedule_id"));

            View v = super.getView(position, convertView, parent);
            ImageView iv_icon = (ImageView) v.findViewById(R.id.icon_notes);

            if (position == line) {
                v.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.colorAccent_trans));
            } else {
                v.setBackgroundColor(ContextCompat.getColor(getActivity(), R.color.color_trans));
            }

            if (schedule_title.equals(getActivity().getString(R.string.schedule_weekend))
                    || schedule_title.equals(getActivity().getString(R.string.schedule_def_title))) {
                sharedPref.edit().putString("hour_" + schedule_id, "false").apply();
            } else {
                sharedPref.edit().putString("hour_" + schedule_id, "true").apply();
            }

            Subjects_helper.switchIcon(getActivity(), schedule_icon, "schedule_color", iv_icon);

            iv_icon.setOnClickListener(new View.OnClickListener() {

                @Override
                public void onClick(View arg0) {

                    final helper_main.Item[] items = {
                            new helper_main.Item(getString(R.string.subjects_color_red), R.drawable.circle_red),
                            new helper_main.Item(getString(R.string.subjects_color_pink),
                                    R.drawable.circle_pink),
                            new helper_main.Item(getString(R.string.subjects_color_purple),
                                    R.drawable.circle_purple),
                            new helper_main.Item(getString(R.string.subjects_color_blue),
                                    R.drawable.circle_blue),
                            new helper_main.Item(getString(R.string.subjects_color_teal),
                                    R.drawable.circle_teal),
                            new helper_main.Item(getString(R.string.subjects_color_green),
                                    R.drawable.circle_green),
                            new helper_main.Item(getString(R.string.subjects_color_lime),
                                    R.drawable.circle_lime),
                            new helper_main.Item(getString(R.string.subjects_color_yellow),
                                    R.drawable.circle_yellow),
                            new helper_main.Item(getString(R.string.subjects_color_orange),
                                    R.drawable.circle_orange),
                            new helper_main.Item(getString(R.string.subjects_color_brown),
                                    R.drawable.circle_brown),
                            new helper_main.Item(getString(R.string.subjects_color_grey),
                                    R.drawable.circle_grey), };

                    ListAdapter adapter = new ArrayAdapter<helper_main.Item>(getActivity(),
                            android.R.layout.select_dialog_item, android.R.id.text1, items) {
                        @NonNull
                        public View getView(int position, View convertView, @NonNull ViewGroup parent) {
                            //Use super class to create the View
                            View v = super.getView(position, convertView, parent);
                            TextView tv = (TextView) v.findViewById(android.R.id.text1);
                            tv.setTextSize(18);
                            tv.setCompoundDrawablesWithIntrinsicBounds(items[position].icon, 0, 0, 0);
                            //Add margin between image and text (support various screen densities)
                            int dp5 = (int) (24 * getResources().getDisplayMetrics().density + 0.5f);
                            tv.setCompoundDrawablePadding(dp5);

                            return v;
                        }
                    };

                    new AlertDialog.Builder(getActivity())
                            .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int whichButton) {
                                    dialog.cancel();
                                }
                            }).setAdapter(adapter, new DialogInterface.OnClickListener() {

                                public void onClick(DialogInterface dialog, int item) {
                                    if (item == 0) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "1",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 1) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "2",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 2) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "3",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 3) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "4",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 4) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "5",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 5) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "6",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 6) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "7",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 7) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "8",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 8) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "9",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 9) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "10",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    } else if (item == 10) {
                                        db.update(Integer.parseInt(_id), schedule_title, schedule_content, "11",
                                                schedule_attachment, schedule_creation, schedule_id);
                                        setScheduleList();
                                    }
                                }
                            }).show();
                }
            });

            return v;
        }
    };

    //display data by filter
    final String note_search = sharedPref.getString("filter_scheduleBY", "schedule_title");
    sharedPref.edit().putString("filter_scheduleBY", "schedule_title").apply();
    filter.addTextChangedListener(new TextWatcher() {
        public void afterTextChanged(Editable s) {
        }

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

        public void onTextChanged(CharSequence s, int start, int before, int count) {
            adapter.getFilter().filter(s.toString());
        }
    });
    adapter.setFilterQueryProvider(new FilterQueryProvider() {
        public Cursor runQuery(CharSequence constraint) {
            return db.fetchDataByFilter(constraint.toString(), note_search);
        }
    });

    lv.setAdapter(adapter);
    //onClick function
    lv.setOnItemClickListener(new AdapterView.OnItemClickListener() {
        @Override
        public void onItemClick(AdapterView<?> adapterview, View view, int position, long id) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String schedule_title = row2.getString(row2.getColumnIndexOrThrow("schedule_title"));

            final CharSequence[] options = { getString(R.string.schedule_todo),
                    getString(R.string.schedule_notes) };
            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.schedule_todo))) {
                                sharedPref.edit().putString("filter_todo_subject", schedule_title).apply();
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        helper_main.switchToActivity(getActivity(), Popup_todo.class, false);
                                    }
                                }, 200);
                            }
                            if (options[item].equals(getString(R.string.schedule_notes))) {
                                sharedPref.edit().putString("filter_note_subject", schedule_title).apply();
                                new Handler().postDelayed(new Runnable() {
                                    public void run() {
                                        helper_main.switchToActivity(getActivity(), Popup_note.class, false);
                                    }
                                }, 200);
                            }
                        }
                    }).show();
        }
    });

    lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
        public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {

            Cursor row2 = (Cursor) lv.getItemAtPosition(position);
            final String _id = row2.getString(row2.getColumnIndexOrThrow("_id"));
            final String schedule_title = row2.getString(row2.getColumnIndexOrThrow("schedule_title"));
            final String schedule_content = row2.getString(row2.getColumnIndexOrThrow("schedule_content"));
            final String schedule_icon = row2.getString(row2.getColumnIndexOrThrow("schedule_icon"));
            final String schedule_attachment = row2
                    .getString(row2.getColumnIndexOrThrow("schedule_attachment"));
            final String schedule_creation = row2.getString(row2.getColumnIndexOrThrow("schedule_creation"));
            final String schedule_id = row2.getString(row2.getColumnIndexOrThrow("schedule_id"));

            final CharSequence[] options = { getString(R.string.number_edit_entry),
                    getString(R.string.bookmark_remove_bookmark), getString(R.string.todo_menu),
                    getString(R.string.bookmark_createNote), getString(R.string.count_create),
                    getString(R.string.bookmark_createEvent) };
            new AlertDialog.Builder(getActivity())
                    .setPositiveButton(R.string.toast_cancel, new DialogInterface.OnClickListener() {

                        public void onClick(DialogInterface dialog, int whichButton) {
                            dialog.cancel();
                        }
                    }).setItems(options, new DialogInterface.OnClickListener() {
                        @SuppressWarnings("ConstantConditions")
                        @Override
                        public void onClick(DialogInterface dialog, int item) {
                            if (options[item].equals(getString(R.string.number_edit_entry))) {

                                final CharSequence[] options = { getString(R.string.schedule_fromSubjectList),
                                        getString(R.string.todo_from_new) };
                                new AlertDialog.Builder(getActivity()).setPositiveButton(R.string.toast_cancel,
                                        new DialogInterface.OnClickListener() {

                                            public void onClick(DialogInterface dialog, int whichButton) {
                                                dialog.cancel();
                                            }
                                        }).setItems(options, new DialogInterface.OnClickListener() {
                                            @Override
                                            public void onClick(DialogInterface dialog, int item) {
                                                if (options[item]
                                                        .equals(getString(R.string.schedule_fromSubjectList))) {
                                                    sharedPref.edit().putString("edit_yes", "true")
                                                            .putInt("scroll", Integer.parseInt(schedule_id))
                                                            .putString("handleSubjectCreation",
                                                                    schedule_creation)
                                                            .putString("handleSubject_id", schedule_id)
                                                            .putString("handle_id", _id).apply();
                                                    helper_main.switchToActivity(getActivity(),
                                                            Popup_subjects.class, false);
                                                }

                                                if (options[item].equals(getString(R.string.todo_from_new))) {

                                                    LayoutInflater inflater = getActivity().getLayoutInflater();

                                                    final ViewGroup nullParent = null;
                                                    View dialogView = inflater
                                                            .inflate(R.layout.dialog_edit_subject, nullParent);

                                                    final EditText titleInput = (EditText) dialogView
                                                            .findViewById(R.id.subject_title_);
                                                    titleInput.setSelection(titleInput.getText().length());
                                                    titleInput.setText(schedule_title);
                                                    final EditText teacherInput = (EditText) dialogView
                                                            .findViewById(R.id.subject_teacher);
                                                    teacherInput.setText(schedule_content);
                                                    final EditText roomInput = (EditText) dialogView
                                                            .findViewById(R.id.subject_room);
                                                    roomInput.setText(schedule_attachment);

                                                    helper_main.showKeyboard(getActivity(), titleInput);

                                                    final ImageButton be = (ImageButton) dialogView
                                                            .findViewById(R.id.imageButtonPri);
                                                    assert be != null;

                                                    Subjects_helper.switchIcon(getActivity(), schedule_icon,
                                                            "schedule_color", be);

                                                    be.setOnClickListener(new View.OnClickListener() {

                                                        @Override
                                                        public void onClick(View arg0) {

                                                            final helper_main.Item[] items = {
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_red),
                                                                            R.drawable.circle_red),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_pink),
                                                                            R.drawable.circle_pink),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_purple),
                                                                            R.drawable.circle_purple),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_blue),
                                                                            R.drawable.circle_blue),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_teal),
                                                                            R.drawable.circle_teal),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_green),
                                                                            R.drawable.circle_green),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_lime),
                                                                            R.drawable.circle_lime),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_yellow),
                                                                            R.drawable.circle_yellow),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_orange),
                                                                            R.drawable.circle_orange),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_brown),
                                                                            R.drawable.circle_brown),
                                                                    new helper_main.Item(getString(
                                                                            R.string.subjects_color_grey),
                                                                            R.drawable.circle_grey), };

                                                            ListAdapter adapter = new ArrayAdapter<helper_main.Item>(
                                                                    getActivity(),
                                                                    android.R.layout.select_dialog_item,
                                                                    android.R.id.text1, items) {
                                                                @NonNull
                                                                public View getView(int position,
                                                                        View convertView,
                                                                        @NonNull ViewGroup parent) {
                                                                    //Use super class to create the View
                                                                    View v = super.getView(position,
                                                                            convertView, parent);
                                                                    TextView tv = (TextView) v
                                                                            .findViewById(android.R.id.text1);
                                                                    tv.setTextSize(18);
                                                                    tv.setCompoundDrawablesWithIntrinsicBounds(
                                                                            items[position].icon, 0, 0, 0);
                                                                    //Add margin between image and text (support various screen densities)
                                                                    int dp5 = (int) (24
                                                                            * getActivity().getResources()
                                                                                    .getDisplayMetrics().density
                                                                            + 0.5f);
                                                                    tv.setCompoundDrawablePadding(dp5);

                                                                    return v;
                                                                }
                                                            };

                                                            new android.app.AlertDialog.Builder(getActivity())
                                                                    .setPositiveButton(R.string.toast_cancel,
                                                                            new DialogInterface.OnClickListener() {

                                                                                public void onClick(
                                                                                        DialogInterface dialog,
                                                                                        int whichButton) {
                                                                                    dialog.cancel();
                                                                                }
                                                                            })
                                                                    .setAdapter(adapter,
                                                                            new DialogInterface.OnClickListener() {
                                                                                public void onClick(
                                                                                        DialogInterface dialog,
                                                                                        int item) {
                                                                                    if (item == 0) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_red);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "1")
                                                                                                .apply();
                                                                                    } else if (item == 1) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_pink);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "2")
                                                                                                .apply();
                                                                                    } else if (item == 2) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_purple);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "3")
                                                                                                .apply();
                                                                                    } else if (item == 3) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_blue);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "4")
                                                                                                .apply();
                                                                                    } else if (item == 4) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_teal);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "5")
                                                                                                .apply();
                                                                                    } else if (item == 5) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_green);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "6")
                                                                                                .apply();
                                                                                    } else if (item == 6) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_lime);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "7")
                                                                                                .apply();
                                                                                    } else if (item == 7) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_yellow);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "8")
                                                                                                .apply();
                                                                                    } else if (item == 8) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_orange);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "9")
                                                                                                .apply();
                                                                                    } else if (item == 9) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_brown);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "10")
                                                                                                .apply();
                                                                                    } else if (item == 10) {
                                                                                        be.setImageResource(
                                                                                                R.drawable.circle_grey);
                                                                                        sharedPref.edit()
                                                                                                .putString(
                                                                                                        "schedule_color",
                                                                                                        "11")
                                                                                                .apply();
                                                                                    }
                                                                                }
                                                                            })
                                                                    .show();
                                                        }
                                                    });

                                                    android.support.v7.app.AlertDialog.Builder builder = new android.support.v7.app.AlertDialog.Builder(
                                                            getActivity());
                                                    builder.setTitle(R.string.subjects_edit);
                                                    builder.setView(dialogView);
                                                    builder.setPositiveButton(R.string.toast_yes,
                                                            new DialogInterface.OnClickListener() {

                                                                public void onClick(DialogInterface dialog,
                                                                        int whichButton) {

                                                                    String inputTitle = titleInput.getText()
                                                                            .toString().trim();
                                                                    String inputTeacher = teacherInput.getText()
                                                                            .toString().trim();
                                                                    String inputRoom = roomInput.getText()
                                                                            .toString().trim();

                                                                    db.update(Integer.parseInt(_id), inputTitle,
                                                                            inputTeacher,
                                                                            sharedPref.getString(
                                                                                    "schedule_color", ""),
                                                                            inputRoom, schedule_creation,
                                                                            schedule_id);
                                                                    dialog.dismiss();
                                                                    setScheduleList();
                                                                    lv.setSelection(
                                                                            Integer.parseInt(schedule_id) - 1);
                                                                    Snackbar.make(lv, R.string.bookmark_added,
                                                                            Snackbar.LENGTH_SHORT).show();
                                                                }
                                                            });
                                                    builder.setNegativeButton(R.string.toast_cancel,
                                                            new DialogInterface.OnClickListener() {

                                                                public void onClick(DialogInterface dialog,
                                                                        int whichButton) {
                                                                    dialog.cancel();
                                                                }
                                                            });

                                                    final android.support.v7.app.AlertDialog dialog2 = builder
                                                            .create();
                                                    dialog2.show();
                                                }

                                            }
                                        }).show();
                            }

                            if (options[item].equals(getString(R.string.bookmark_remove_bookmark))) {
                                Snackbar snackbar = Snackbar
                                        .make(lv, R.string.note_remove_confirmation, Snackbar.LENGTH_LONG)
                                        .setAction(R.string.toast_yes, new View.OnClickListener() {
                                            @Override
                                            public void onClick(View view) {
                                                db.update(Integer.parseInt(_id),
                                                        getString(R.string.schedule_def_teacher),
                                                        getString(R.string.schedule_def_teacher), "11",
                                                        getString(R.string.schedule_def_teacher),
                                                        schedule_creation, schedule_id);
                                                setScheduleList();
                                                lv.setSelection(Integer.parseInt(schedule_id) - 1);
                                            }
                                        });
                                snackbar.show();
                            }

                            if (options[item].equals(getString(R.string.todo_menu))) {
                                Todo_helper.newTodo(getActivity(), schedule_title, schedule_content,
                                        getActivity().getString(R.string.note_content));
                            }

                            if (options[item].equals(getString(R.string.count_create))) {
                                Count_helper.newCount(getActivity(), schedule_title, schedule_content,
                                        getActivity().getString(R.string.note_content), false);
                            }

                            if (options[item].equals(getString(R.string.bookmark_createEvent))) {
                                helper_main.createCalendarEvent(getActivity(), schedule_title,
                                        schedule_content);
                            }

                            if (options[item].equals(getString(R.string.bookmark_createNote))) {
                                Notes_helper.newNote(getActivity(), schedule_title, schedule_content, "", "",
                                        "", "");
                            }

                        }
                    }).show();
            return true;
        }
    });

    scrollToNow();
}

From source file:com.mylikes.likes.etchasketch.Slate.java

public void promptForText(final int x, final int y, final TextDrawing drawing) {
    LayoutInflater li = LayoutInflater.from(getContext());
    View promptsView = li.inflate(R.layout.prompts, null);
    AlertDialog.Builder alertDialogBuilder = new AlertDialog.Builder(getContext());

    // set prompts.xml to alertdialog builder
    alertDialogBuilder.setView(promptsView);

    final EditText userInput = (EditText) promptsView.findViewById(R.id.editTextDialogUserInput);
    if (drawing != null) {
        String text = drawing.getText();
        userInput.setText(text);//  www. j  av a2  s  .c om
        userInput.setSelection(text.length());
    }

    // TODO: add font dropdown to dialog
    alertDialogBuilder.setCancelable(false).setPositiveButton("OK", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            if (drawing != null) {
                drawing.setText(userInput.getText().toString());
                invalidate();
            } else {
                addText(x, y, userInput.getText().toString());
            }
        }
    }).setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
        public void onClick(DialogInterface dialog, int id) {
            dialog.cancel();
        }
    });

    alertDialogBuilder.create().show();
}