問題描述
我想實(shí)現(xiàn)一個(gè)自定義文本界面,觸摸+拖動(dòng)選擇文本并且鍵盤不被抬起,這與長按打開 CCP 菜單和鍵盤的默認(rèn)行為形成對比.我的理解表明我需要這種方法:
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
}
我已經(jīng)了解了所有關(guān)于 getSelectStart() 和設(shè)置范圍等的各種方法,但我找不到如何根據(jù)觸摸事件 getX() 和 getY() 獲取文本位置.有沒有辦法做到這一點(diǎn)?我已經(jīng)在其他辦公應(yīng)用中看到了我想要的行為.
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.
另外,在手動(dòng)請求之前,我將如何阻止鍵盤出現(xiàn)?
Also, how would I stop the keyboard appearing until manually requested?
推薦答案
"mText.setInputType(InputType.TYPE_NULL)" 在 Android 3.0 及以上版本下會(huì)抑制軟鍵盤,但也會(huì)禁用 EditText 框中閃爍的光標(biāo).我編寫了一個(gè) onTouchListener 并返回 true 以禁用鍵盤,然后必須從運(yùn)動(dòng)事件中獲取觸摸位置以將光標(biāo)設(shè)置到正確的位置.您可以在 ACTION_MOVE 運(yùn)動(dòng)事件上??使用它來選擇要拖動(dòng)的文本.
"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);
這篇關(guān)于android:如何從觸摸事件中獲取文本位置的文章就介紹到這了,希望我們推薦的答案對大家有所幫助,也希望大家多多支持html5模板網(wǎng)!