我有一个TextView
. 当它被长按时,长按的那段文本应该被突出显示,并且应该出现一个上下文操作菜单,它提供了一些额外的选项。
但是,如果文本被突出显示,则上下文操作菜单与所需的不同。另一方面,如果显示了所需的上下文操作菜单,则不会突出显示文本。
我已经能够将它return
归零onLongClick
为onLongClickListener
. 具体来说,如果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;
}
};
}
}
我的问题:
1.如何覆盖的默认行为TextView
?
2. 如何通过上下文操作菜单获得文本选择?