我有一個TextView
。當它被長時間點擊時,應該突出顯示完成長按操作的那段文本,並且應該出現一個上下文操作菜單,以提供一些其他選項。覆蓋longClick上的默認行爲()
但是,如果文本突出顯示,則上下文操作菜單與所需內容不同。另一方面,如果顯示了所需的上下文操作菜單,則文本不會突出顯示。
我已經能夠將其歸爲的onLongClick
函數中的return
語句。具體而言,如果onLongClick
函數returns true
(消耗點擊),則會顯示上下文操作菜單,但由於長時間點擊從未傳遞給文本選擇工具,因此它不會被激活。但是,如果onLongClick
函數返回false
,則會將該點擊傳遞給一個函數,該函數會觸發具有選擇的文本的默認行爲copy + paste
。
代碼:
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.TextView;
public class HelloTxtView extends Activity {
//private EditText ed;
private TextView ed;
//actionmode callback.
private ActionMode mActionMode;
private ActionMode.Callback mActionModeCallback;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_hello_txt_view);
ed = (TextView) findViewById(R.id.txtview);
ed.setFocusable(true);
ed.setText("Hello World! Let's select some text!!");
initActionModeCallbacks();
ed.setOnLongClickListener(new View.OnLongClickListener() {
@Override
public boolean onLongClick(View v) {
Log.v(this.toString(), "Long click.");
ed.setCursorVisible(true);
Log.v(this.toString(), "Starting actionmodecallback.");
mActionMode = HelloTxtView.this.startActionMode(mActionModeCallback);
v.setSelected(true);
return false;
}
});
}
public void initActionModeCallbacks() {
/*
* This function initializes the callbacks.
*/
mActionModeCallback = new ActionMode.Callback() {
@Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
//nothing to do here.
Log.v(this.toString(), "Preparing action mode.");
return false;
}
@Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(this.toString(), "Destroy action mode.");
//mActionModeCallback = null;
}
@Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(this.toString(), "Creating new action mode menu.");
//inflate a new menu.
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.options_menu, menu);
Log.v(this.toString(), "Done inflating menu.");
return true;
}
@Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
Log.v(this.toString(), "An item was clicked.");
switch(item.getItemId()) {
case R.id.dictLookup:
Log.v(this.toString(), "Look up dictionary.");
break;
case R.id.readFromHere:
Log.v(this.toString(), "Start reading from here:" + ed.getSelectionStart());
}
return false;
}
};
}
}
我的問題(S):
1.如何重寫TextView
的默認行爲?
2.如何使用上下文操作菜單獲取文本選擇?