có vẻ không có nhiều bạn có thể làm bằng cách sử dụng các API: android paste event
Source reading to the rescue!
tôi đào vào Nguồn Android của TextView
(EditText
là một TextView
với một số cấu hình khác nhau) và phát hiện ra rằng menu được sử dụng để cung cấp tùy chọn cắt/sao chép/dán chỉ là một sửa đổi ContextMenu
(source).
Đối với menu ngữ cảnh thông thường, Chế độ xem phải tạo menu (source) và sau đó xử lý tương tác trong phương thức gọi lại (source).
Vì phương thức xử lý là public
, chúng ta có thể chỉ cần móc vào nó bằng cách mở rộng EditText
và ghi đè phương thức phản ứng trên các hành động khác nhau. Dưới đây là một ví dụ-thực hiện:
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();
}
}
Bây giờ, khi người dùng sử dụng cut/copy/paste, một Toast
được hiển thị (tất nhiên bạn có thể làm những việc khác nữa).
Điều gọn gàng là này hoạt động xuống Android 1.5 và bạn không cần phải tạo lại menu ngữ cảnh (như gợi ý trong câu hỏi liên kết ở trên), mà sẽ giữ giao diện liên tục của nền tảng (ví dụ với HTC Sense).
Nguồn
2013-02-20 13:44:50
Thách thức tốt. Nhìn vào câu trả lời của tôi. –