0

我有几个TextView和几个EditText,我想从中选择一个数据子字符串来复制 API 级别 10 及更高级别。我已经OnLongClickListener为这个问题实现了一个,但它(可以理解)抛出一个ArrayOutOfBoundsException

   public boolean onLongClick(View v) {
    // TODO Auto-generated method stub
    //copy
    longPressedView=v;
    startSelection=((TextView)v).getSelectionStart();
    endSelection=((TextView)v).getSelectionEnd();
    Log.d(TAG, "Selection starts at "+startSelection+" and ends at "+endSelection);
    if(startSelection>endSelection)
    {
        startSelection=startSelection+endSelection;
        endSelection=startSelection-endSelection;
        startSelection=startSelection-endSelection;
        Log.d(TAG, "After interchanging positions selection starts at "+startSelection+" and ends at "+endSelection);
    }
    mSelectedText=((TextView)v).getText().toString().substring(startSelection, endSelection);
    mActionMode=startActionMode(actionModeCallback);
    return true;
}

我曾考虑过实现 OnTouchListener,但这只会返回对我没有用的 x 和 y 位置。

 java.lang.StringIndexOutOfBoundsException: length=93; regionStart=-1; regionLength=0
 at java.lang.String.startEndAndLength(String.java:583)
 at java.lang.String.substring(String.java:1464)
 at com.example.clipboardtest.MainActivity.onClick(MainActivity.java:139)
 at android.view.View.performClick(View.java:4240)
 at android.view.View$PerformClick.run(View.java:17721)
 at android.os.Handler.handleCallback(Handler.java:730)
 at android.os.Handler.dispatchMessage(Handler.java:92)
 at android.os.Looper.loop(Looper.java:137)
 at android.app.ActivityThread.main(ActivityThread.java:5103)
 at java.lang.reflect.Method.invokeNative(Native Method)
 at java.lang.reflect.Method.invoke(Method.java:525)
 at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:737)
 at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:553)
 at dalvik.system.NativeStart.main(Native Method)
4

2 回答 2

1

首先在你的xml中的textview中添加这个属性: -

android:textIsSelectable="true"

然后使用此代码:-

    t = (TextView)findViewById(R.id.textView1);
    t.setOnLongClickListener(new View.OnLongClickListener() {

        @Override
        public boolean onLongClick(View v) {

            int start = t.getSelectionStart();
            int end = t.getSelectionEnd();
            if(start == -1 && end == -1){
                return true;
            }
            String mSelectedText=((TextView)v).getText().toString().substring(start, end);
            System.out.println(mSelectedText);

            return false;
        }
    });
于 2013-11-12T09:36:52.337 回答
0

OnClickListener 怎么样?

text_field.setOnClickListener(new View.OnClickListener()
        {
            public void onClick(View v)
            {
                //-------- Your code goes here
            }
        });
于 2013-11-12T08:54:56.410 回答