2012-02-01 58 views
4

我正在使用EditText小部件,並且想要修改用戶長按視圖時顯示的上下文菜單。我遇到的問題是我需要知道長按的文本內的字符位置,以便我可以確定需要添加到上下文菜單中的內容。基類正在這樣做,因爲菜單中的一個選項是「添加」word_clicked_on「To Dictionary」。在文本中設置ClickableSpans似乎不是一個解決方案,因爲它消耗了單擊事件,從而無法在跨度內移動編輯光標。基於長按位置動態修改EditText中的上下文/長按菜單

回答

4

這裏是我想出了一個解決方案,它的工作,所以我想分享:

首先,我的結論是,我需要延長的EditText類,這樣我可以攔截的onTouchEvent,捕捉ACTION_DOWN事件,並保存位置。現在我可以調用getOffsetForPosition(downPointX,downPointY)並獲得長按的字符位置。有一個大問題,getOffsetForPosition在SDK 14之前沒有添加!爲了使這個解決方案的工作,我不得不回港getOffsetForPosition的功能和分支如果當前SDK比SDK_INT 14.這是較早對新類的源代碼:

public class ScrapEditText extends EditText{ 

protected float LastDownPositionX, LastDownPositionY; 

public ScrapEditText(Context context) 
{ 
    super(context); 
} 

public ScrapEditText(Context context, AttributeSet attrs) 
{ 
    super(context, attrs); 
} 

@Override 
public boolean onTouchEvent(MotionEvent event) 
{ 
    final int action = event.getActionMasked(); 
    if(action == MotionEvent.ACTION_DOWN) 
    { 
     LastDownPositionX = event.getX(); 
     LastDownPositionY = event.getY(); 
    } 
    return super.onTouchEvent(event); 
} 

public float GetLastDownPositionX() 
{ 
    return LastDownPositionX; 
} 

public float GetLastDownPositionY() 
{ 
    return LastDownPositionY; 
} 

public int GetOffsetForLastDownPosition() 
{ 

    if(Build.VERSION.SDK_INT > 13) 
    { 
     // as of SDK 14 the getOffsetForPosition was added to TextView 
     return getOffsetForPosition(LastDownPositionX, LastDownPositionY); 
    } 
    else 
    { 
     return GetOffsetForPositionOlderSdk(); 
    } 
} 

public int GetOffsetForPositionOlderSdk() 
{ 
    if (getLayout() == null) return -1; 
    final int line = GetLineAtCoordinateOlderSDK(LastDownPositionY); 
    final int offset = GetOffsetAtCoordinateOlderSDK(line, LastDownPositionX); 
    return offset; 
} 

public int GetLineAtCoordinateOlderSDK(float y) 
{ 
    y -= getTotalPaddingTop(); 
    // Clamp the position to inside of the view. 
    y = Math.max(0.0f, y); 
    y = Math.min(getHeight() - getTotalPaddingBottom() - 1, y); 
    y += getScrollY(); 
    return getLayout().getLineForVertical((int) y);  
} 

protected int GetOffsetAtCoordinateOlderSDK(int line, float x) { 
    x = ConvertToLocalHorizontalCoordinateOlderSDK(x); 
    return getLayout().getOffsetForHorizontal(line, x); 
} 

protected float ConvertToLocalHorizontalCoordinateOlderSDK(float x) { 
    x -= getTotalPaddingLeft(); 
    // Clamp the position to inside of the view. 
    x = Math.max(0.0f, x); 
    x = Math.min(getWidth() - getTotalPaddingRight() - 1, x); 
    x += getScrollX(); 
    return x; 
} 

} 

在你的活動派生類:

ScrapText = (ScrapEditText) findViewById(R.id.sample_text); 
ScrapText.setOnCreateContextMenuListener(new View.OnCreateContextMenuListener(){ 

@Override 
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenuInfo menuInfo) 
{ 
    int charOffset = FileText.GetOffsetForLastDownPosition(); 
}   
});