使用 API 似乎无能为力:android paste event
Source reading to the rescue!
我深入研究了TextView 的Android 源代码(EditText 是具有一些不同配置的TextView)并发现用于提供剪切/复制/粘贴选项的菜单只是修改后的@987654323 @ (source)。
对于普通的上下文菜单,视图必须创建菜单 (source),然后在回调方法 (source) 中处理交互。
由于处理方法是public,我们可以简单地通过扩展EditText 并覆盖该方法以对不同的操作作出反应来挂钩它。这是一个示例实现:
import android.content.Context;
import android.util.AttributeSet;
import android.widget.EditText;
import android.widget.Toast;
/**
* An EditText, which notifies when something was cut/copied/pasted inside it.
* @author Lukas Knuth
* @version 1.0
*/
public class MonitoringEditText extends EditText {
private final Context context;
/*
Just the constructors to create a new EditText...
*/
public MonitoringEditText(Context context) {
super(context);
this.context = context;
}
public MonitoringEditText(Context context, AttributeSet attrs) {
super(context, attrs);
this.context = context;
}
public MonitoringEditText(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
this.context = context;
}
/**
* <p>This is where the "magic" happens.</p>
* <p>The menu used to cut/copy/paste is a normal ContextMenu, which allows us to
* overwrite the consuming method and react on the different events.</p>
* @see <a href="http://grepcode.com/file/repository.grepcode.com/java/ext/com.google.android/android/2.3_r1/android/widget/TextView.java#TextView.onTextContextMenuItem%28int%29">Original Implementation</a>
*/
@Override
public boolean onTextContextMenuItem(int id) {
// Do your thing:
boolean consumed = super.onTextContextMenuItem(id);
// React:
switch (id){
case android.R.id.cut:
onTextCut();
break;
case android.R.id.paste:
onTextPaste();
break;
case android.R.id.copy:
onTextCopy();
}
return consumed;
}
/**
* Text was cut from this EditText.
*/
public void onTextCut(){
Toast.makeText(context, "Cut!", Toast.LENGTH_SHORT).show();
}
/**
* Text was copied from this EditText.
*/
public void onTextCopy(){
Toast.makeText(context, "Copy!", Toast.LENGTH_SHORT).show();
}
/**
* Text was pasted into the EditText.
*/
public void onTextPaste(){
Toast.makeText(context, "Paste!", Toast.LENGTH_SHORT).show();
}
}
现在,当用户使用剪切/复制/粘贴时,会显示Toast(当然你也可以做其他事情)。
巧妙的是,这适用于 Android 1.5,您无需重新创建上下文菜单(如上述链接问题中所建议的那样),这将 保持平台外观不变(例如使用 HTC Sense)。