問題描述
我想實現一個自定義文本界面,觸摸+拖動選擇文本并且鍵盤不被抬起,這與長按打開 CCP 菜單和鍵盤的默認行為形成對比.我的理解表明我需要這種方法:
I'm wanting to implement a custom text interface, with touch+drag selecting text and the keyboard not being raised, in contrast to the default behavior of a long-click bringing up the CCP menu and the keyboard. My understanding suggests I need this approach:
onTouchEvent(event){
case touch_down:
get START text position
case drag
get END text position
set selection range from START to END
}
我已經了解了所有關于 getSelectStart() 和設置范圍等的各種方法,但我找不到如何根據觸摸事件 getX() 和 getY() 獲取文本位置.有沒有辦法做到這一點?我已經在其他辦公應用中看到了我想要的行為.
I've found out all about getSelectStart() and various methods to setting a range and such, but I cannot find how to get the text position based on a touch event getX() and getY(). Is there any way to do this? I've seen the behaviour I want in other office apps.
另外,在手動請求之前,我將如何阻止鍵盤出現?
Also, how would I stop the keyboard appearing until manually requested?
推薦答案
"mText.setInputType(InputType.TYPE_NULL)" 在 Android 3.0 及以上版本下會抑制軟鍵盤,但也會禁用 EditText 框中閃爍的光標.我編寫了一個 onTouchListener 并返回 true 以禁用鍵盤,然后必須從運動事件中獲取觸摸位置以將光標設置到正確的位置.您可以在 ACTION_MOVE 運動事件上??使用它來選擇要拖動的文本.
"mText.setInputType(InputType.TYPE_NULL)" will suppress the soft keyboard but it also disables the blinking cursor in an EditText box under Android 3.0 and above. I coded an onTouchListener and returned true to disable the keyboard and then had to get the touch position from the motion event to set the cursor to the correct spot. You might be able to use this on an ACTION_MOVE motion event to select text for dragging.
這是我使用的代碼:
mText = (EditText) findViewById(R.id.editText1);
OnTouchListener otl = new OnTouchListener() {
@Override
public boolean onTouch(View v, MotionEvent event) {
switch (event.getAction()) {
case MotionEvent.ACTION_DOWN:
Layout layout = ((EditText) v).getLayout();
float x = event.getX() + mText.getScrollX();
int offset = layout.getOffsetForHorizontal(0, x);
if(offset>0)
if(x>layout.getLineMax(0))
mText.setSelection(offset); // touch was at end of text
else
mText.setSelection(offset - 1);
break;
}
return true;
}
};
mText.setOnTouchListener(otl);
這篇關于android:如何從觸摸事件中獲取文本位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網!