Textview中的onClick和onLongClick选择

时间:2014-03-21 01:10:49

标签: java android selection onlongclicklistener

我已经搜索了这个问题的答案了几天没有结果。当在TextView上使用onClick时,我得到了通过使用选择单击单词所需的结果:

    textView.setOnLongClickListener(new View.OnLongClickListener() {            
        @Override
        public boolean onLongClick(final View arg0) {
            Spannable span = (Spannable)textView.getText();
            Layout layout = textView.getLayout();

            Toast.makeText(arg0.getContext(), "Selection: " + Selection.getSelectionStart(textView.getText().toString()) + Selection.getSelectionEnd(textView.getText().toString()), Toast.LENGTH_SHORT).show();
            // returns -1, -1
            Toast.makeText(arg0.getContext(), "Selection: " + textView.getSelectionStart() + textView.getSelectionEnd(), Toast.LENGTH_SHORT).show();
            //returns -1, -1

            Selection.moveToLeftEdge(span, layout);
            Selection.extendToRightEdge(span, layout);

            final int start = textView.getSelectionStart();
            final int end = textView.getSelectionEnd();
            String string = textView.getText().toString().substring(start, end);                

            AlertDialog.Builder builder = new AlertDialog.Builder(arg0.getContext());
            builder.setTitle("Delete: " + string)
            .setMessage("Are you sure? This operation can't be undone!")
            .setCancelable(false)
            .setPositiveButton("OK", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                    deleteItem(start, end);
                }
            })
            .setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
                public void onClick(DialogInterface dialog, int id) {
                }
            })
            .show();
            return true;
        }
    });

    textView.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View arg0) {
            Spannable span = (Spannable)textView.getText();
            Layout layout = textView.getLayout();
            Selection.moveToLeftEdge(span, layout);
            Selection.extendToRightEdge(span, layout);
            writeStrikes(textView.getSelectionStart(), textView.getSelectionEnd());             
        }           
    });

当我尝试对onLongClick使用相同的代码时,选择为-1,-1。如果我从onLongClick返回false,则下一个选择应该是最后一个。因此,在调用onLongClick之后,当用户释放长按时,将设置光标。如何在调用onLongClick()之前将光标设置为长按的位置?

0 个答案:

没有答案