gpt4 book ai didi

Android在editText上拦截粘贴\复制\剪切

转载 作者:IT老高 更新时间:2023-10-28 21:40:08 27 4
gpt4 key购买 nike

如何拦截此类事件?

当用户尝试将一些文本粘贴到我的 EditText 中时,我需要添加一些逻辑我知道我可以使用 TextWatcher 但这个入口点对我不利,因为我只在粘贴的情况下需要拦截,而不是每次用户按下我的 EditText,

最佳答案

使用 API 似乎无能为力:android paste event

Source reading to the rescue!

我挖掘了 TextView 的 Android 源码(EditText 是一个 TextView 有一些不同的配置),发现菜单使用提供剪切/复制/粘贴选项只是修改后的ContextMenu (source)。

对于普通的上下文菜单, View 必须创建菜单(source),然后在回调方法(source)中处理交互。

因为处理方法是 public,我们可以简单地通过扩展 EditText 并覆盖该方法以对不同的操作使用react来 Hook 它。这是一个示例实现:

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)。

关于Android在editText上拦截粘贴\复制\剪切,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/14980227/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com