我有一些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;
}
:
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)
我已经考虑过实现OnTouchListener,但这只会返回对我来说毫无用处的x和y位置。
{{1}}
答案 0 :(得分: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;
}
});
答案 1 :(得分:0)
OnClickListener怎么样?
text_field.setOnClickListener(new View.OnClickListener()
{
public void onClick(View v)
{
//-------- Your code goes here
}
});