Using LinkMovementMethod and Native copy/paste in Textview - Android - android

I have a TextView with html text and I need native copy/paste and clickable links.
I have used the next code, but when I use
setMovementMethod(LinkMovementMethod.getInstance());
the native copy/paste stops to work.
If I change setMovementMethod(LinkMovementMethod.getInstance())
to ArrowKeyMovementMethod, the copy/paste works but the click links stops to work.
I don´t posted all code but setMovementMethod is used in updateDetail method.
Does someome can help me?
Regards, Luiz
My code is:
textDetail = (TextView) view.findViewById(R.id.text_detail);
textDetail.setTextIsSelectable(true);
textDetail.setCustomSelectionActionModeCallback(new ActionMode.Callback()
{
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return true;
}
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
return false;
}
});
protected void makeLinkClickable(SpannableStringBuilder strBuilder,
final URLSpan span) {
int start = strBuilder.getSpanStart(span);
int end = strBuilder.getSpanEnd(span);
int flags = strBuilder.getSpanFlags(span);
ClickableSpan clickable = new ClickableSpan() {
#Override
public void onClick(View view) {
}
////////
else {
///////////////
}
}
};
strBuilder.setSpan(clickable, start, end, flags);
strBuilder.removeSpan(span);
}
protected void setTextViewHTML(TextView text, String html) {
CharSequence sequence = Html.fromHtml(html);
SpannableStringBuilder strBuilder = new SpannableStringBuilder(sequence);
URLSpan[] urls = strBuilder.getSpans(0, sequence.length(),
URLSpan.class);
for (URLSpan span : urls) {
makeLinkClickable(strBuilder, span);
}
text.setText(strBuilder);
}
public void updateDetail(String msg) {
setTextViewHTML(textDetail, msg);
textDetail.setMovementMethod(LinkMovementMethod.getInstance());
}

Related

Highlighting textview with color like Adobe PDF

I'm trying to add menu to focus textview to highlight a word or phrase.
Currently my code has issues
1. highlights more than one word if the word appears more than once
2. Highlighted color disappears on app exit.
TextView textView = (TextView) findViewById(R.id.textView);
textView.setCustomSelectionActionModeCallback(new ActionMode.Callback() {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
getMenuInflater().inflate(R.menu.h_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.highlight:
setTextBG();
return true;
default:
break;
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
private void setTextBG() {
String selectedText = "";
if (textView.isFocused()) {
final int textStartIndex = textView.getSelectionStart();
final int textEndIndex = textView.getSelectionEnd();
int min = 0;
int max = textView.getText().length();
min = Math.max(0, Math.min(textStartIndex, textEndIndex));
max = Math.max(0, Math.max(textStartIndex, textEndIndex));
selectedText = textView.getText().subSequence(min, max).toString().trim();
}
int txt = textView.getText().toString().indexOf(selectedText, 0);
Spannable mywords = new SpannableString(textView.getText().toString());
for (int i = 0; i < textView.getText().toString().length() && whateva != -1;
i = whateva+1) {
txt = textView.getText().toString().indexOf(selectedText, i);
if (txt == -1) break;
else {
mywords.setSpan(new BackgroundColorSpan(Color.YELLOW), txt, txt+selectedText.length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
textView.setText(mywords, TextView.BufferType.SPANNABLE);
}
}
Toast.makeText(getApplicationContext(), selectedText, Toast.LENGTH_SHORT).show();
}
Please find below example for highlighting more than one word in content.
MainActivity.java
public class MainActivity extends AppCompatActivity {
private TextView textContent;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
textContent = (TextView) findViewById(R.id.txtContent);
highlightWords();
}
private void highlightWords() {
String content = "This is just a demo of how to highlight more than one word in Android";
textContent.setText(getSpannableWord(content));
}
private Spannable getSpannableWord(String content) {
Spannable spannableString = new SpannableString(content);
// Create list of highlighted word and add to list every time user highlights
ArrayList<HighlightedWord> words = new ArrayList<>();
//1st highlighted word
HighlightedWord highlightedWord1 = new HighlightedWord("demo", 15);
words.add(highlightedWord1);
//2nd highlighted word
HighlightedWord highlightedWord2 = new HighlightedWord("highlight", 30);
words.add(highlightedWord2);
for (HighlightedWord highlightedWord : words) {
spannableString.setSpan(new BackgroundColorSpan(Color.YELLOW), highlightedWord.getStartIndex(),
highlightedWord.getStartIndex()+ highlightedWord.getWord().length(), Spannable
.SPAN_EXCLUSIVE_EXCLUSIVE);
}
return spannableString;
}
}
Thanks!

Customize android search widget for scoped search

I want to implement search filter in my android application. I have gone through the examples on how to integrate search filter and able to understand how to integrate it in application. But my requirement is to provide scoped search based a filter while doing search. I have tried to search similar implementations but was not able to find any examples. Please check section Scoped Search in this UI Pattern collection, especially Dropbox example for iphone.
As mentioned before I was unable to find similar example in android but by looking at Dictionary.com 's application (snapshot shown below) I came to know that its possible in android also (of course by adding some more efforts in case its not possible with Search Widget itself). Can any one please provide any directions how I can implement similar scoped search in my application ?
Thanks for spending time on this.
I would do the following:
first i create a searchType layout for the alertdialog with the choose: (images, video, etc..)
then i create the activity for the search and implement the widget(like on android guide).
in the activity create a variable:
private String searchType = "";
then
...
#Override
public boolean onCreateOptionsMenu(Menu menu) {
super.onCreateOptionsMenu(menu);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.YOUR_MENU, menu);
MenuItem menuItem = menu.findItem(R.id.action_search);
SearchView searchView = (SearchView) MenuItemCompat
.getActionView(menuItem);
searchView.setOnQueryTextListener(new SearchView.OnQueryTextListener() {
//HERE INSERT THE CODE ABOUT THE ALERT DIALOG FOR THE CHOOSE
//THEN INSERT THE aALERT DIALOG RESPONSE INTO THE searchType VARIABLE
}
}
I have created a custom search widget that does not make use of the built in search functionality. Its simple to implement and can provide information to the current activity.
It also uses an Autocomplete textview so you can use Autocomplete, you could alternatively just replace this with a normal EditText.
public class CustomViewSearch extends View {
private CustomAutoCompleteView searchEditText;
private boolean viewShown = false;
private ActionBar actionBar;
private InputMethodManager inputMethodManager;
private OnEditorActionSearchListener onEditorActionSearchListener;
private List<String> dataItems;
private ArrayAdapter<String> arrayAdapter;
public interface OnEditorActionSearchListener {
void onEditorActionSearch(String searchText);
void onTextChangedListener(String text);
List<String> getNewItemsForSuggestions(String text);
}
public void setOnEditorActionSearchListener(OnEditorActionSearchListener l) {
onEditorActionSearchListener = l;
}
// IMPORTANT: Provide your activity as the context
public CustomViewSearch(final Context context, List<String> items) {
super(context);
LayoutInflater inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
View searchView = inflater.inflate(R.layout.custom_view_search_widget, null);
actionBar = ((ActionBarActivity) context).getSupportActionBar();
inputMethodManager = (InputMethodManager) context.getSystemService(Context.INPUT_METHOD_SERVICE);
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setCustomView(searchView);
actionBar.setDisplayShowCustomEnabled(true);
dataItems = items;
searchEditText = (CustomAutoCompleteView) searchView.findViewById(R.id.edit_text_search);
searchEditText.setOnEditorActionListener(new TextView.OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId, KeyEvent event) {
if (actionId == EditorInfo.IME_ACTION_SEARCH) {
onEditorActionSearchListener.onEditorActionSearch(searchEditText.getText().toString());
return true;
}
return false;
}
});
searchEditText.requestFocus();
searchEditText.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
onEditorActionSearchListener.onTextChangedListener(s.toString());
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
dataItems = onEditorActionSearchListener.getNewItemsForSuggestions(s.toString());
// update the adapater
arrayAdapter = new ArrayAdapter<String>(context, android.R.layout.simple_dropdown_item_1line, dataItems);
arrayAdapter.notifyDataSetChanged();
searchEditText.setAdapter(arrayAdapter);
}
});
ImageButton closeImageButton = (ImageButton) searchView.findViewById(R.id.image_button_search_close);
closeImageButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (searchEditText.getText().length() > 0) {
searchEditText.setText("");
} else {
hideKeyboard();
actionBar.setDisplayShowTitleEnabled(true);
actionBar.setDisplayShowCustomEnabled(false);
viewShown = false;
}
}
});
viewShown = true;
showKeyboard();
}
public String actionClick() {
if (!viewShown) {
actionBar.setDisplayShowTitleEnabled(false);
actionBar.setDisplayShowCustomEnabled(true);
searchEditText.requestFocus();
showKeyboard();
viewShown = true;
return null;
} else {
return getSearchText();
}
}
public void showKeyboard() {
inputMethodManager.showSoftInput(searchEditText, InputMethodManager.SHOW_IMPLICIT);
}
public void hideKeyboard() {
inputMethodManager.hideSoftInputFromWindow(searchEditText.getWindowToken(), 0);
}
public String getSearchText() {
return searchEditText.getText().toString();
} }
The corresponding xml layout for the search :
<?xml version="1.0" encoding="utf-8"?>
<za.co.android.CustomAutoCompleteView android:id="#+id/edit_text_search"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_toLeftOf="#+id/empty_layout"
android:paddingBottom="8dp"
android:textColor="#android:color/white"
android:singleLine="true"
android:imeOptions="actionSearch"
android:textCursorDrawable="#null"
android:paddingRight="36dp"
android:layout_alignParentLeft="true"
android:inputType="text"
android:hint="#string/search"
android:textColorHint="#color/palette_primary_light_grey"/>
<ImageButton
android:id="#+id/image_button_search_close"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:background="#android:drawable/ic_menu_close_clear_cancel"
android:layout_toLeftOf="#+id/empty_layout"
android:layout_centerVertical="true"
android:layout_marginRight="4dp"/>
<FrameLayout
android:id="#+id/empty_layout"
android:layout_width="0dp"
android:layout_height="0dp"
android:layout_alignParentRight="true">
</FrameLayout>
The custom autocomplete widget code:
public class CustomAutoCompleteView extends AutoCompleteTextView {
public CustomAutoCompleteView(Context context) {
super(context);
// TODO Auto-generated constructor stub
}
public CustomAutoCompleteView(Context context, AttributeSet attrs) {
super(context, attrs);
// TODO Auto-generated constructor stub
}
public CustomAutoCompleteView(Context context, AttributeSet attrs, int defStyle) {
super(context, attrs, defStyle);
// TODO Auto-generated constructor stub
}
// this is how to disable AutoCompleteTextView filter
#Override
protected void performFiltering(final CharSequence text, final int keyCode) {
String filterText = "";
super.performFiltering(filterText, keyCode);
}
/*
* after a selection we have to capture the new value and append to the existing text
*/
#Override
protected void replaceText(final CharSequence text) {
super.replaceText(text);
}}
Usage of the CustomViewSearch widget:
Add a search icon to the menu.xml for the Activity. Then in the onOptionsItemSelected method - when the menu item is clicked, call the below function:
public void triggerSearch() {
if (customViewSearch == null) {
customViewSearch = new CustomViewSearch(this, null);
customViewSearch.setOnEditorActionSearchListener(new CustomViewSearch.OnEditorActionSearchListener() {
#Override
public void onEditorActionSearch(String searchText) {
// DO SOME STUFF
((AppItemListFragment_) getSupportFragmentManager()
.findFragmentById(R.id.appitem_list)).searchTriggered(searchText);
}
#Override
public void onTextChangedListener(String text) {
((AppItemListFragment_) getSupportFragmentManager()
.findFragmentById(R.id.appitem_list)).searchTriggered(text);
}
#Override
public List<String> getNewItemsForSuggestions(String text) {
return getNewAutoCompleteStrings(text);
}
});
} else {
String searchText = customViewSearch.actionClick();
if (searchText != null) {
// DO SOME STUFF
((AppItemListFragment_) getSupportFragmentManager()
.findFragmentById(R.id.appitem_list)).searchTriggered(searchText);
}
}}
I hope this helps - for me it was much easier to implement a custom search than use the built in one and provides a scoped search for any screen you are on.

Using native look and feel of the searchView for actionBarSherlock on old Android versions

I've noticed that there is no working solution that shows how to use filter on a listView items using the actionbar, that works on older Android versions (like 2.3.x).
The only example I've found is in the file "LoaderCursorSupport.java" of the fragments example. However, it only works when the searchView can be created, meaning starting from Android 3.x, as shown in the code:
View searchView=SearchViewCompat.newSearchView(getActivity());
if(searchView!=null)
...
The above bug (or missing feature, whichever way you look at it) still exist even on version 4.2 of actionBarSherlock.
So I've made my own solution, which works great (and I wish the official library could add my fix to it too), but I don't know where to get the "x" button within the editText view that is responsible for clearing the text.
Can anyone please tell me how to get the native look and feel and put it correctly in the code?
Here's a screenshot of what i'm talking about:
For those wish to use this feature, here is my code snippet :
#Override
public boolean onCreateOptionsMenu(final com.actionbarsherlock.view.Menu menu)
{
getSupportMenuInflater().inflate(R.menu.activity_main,menu);
_searchMenuItem=menu.findItem(R.id.menu_item_action_search);
View searchView=SearchViewCompat.newSearchView(this);
if(searchView!=null)
SearchViewCompat.setOnQueryTextListener(searchView,new OnQueryTextListenerCompat()
{
#Override
public boolean onQueryTextChange(final String newText)
{
_listAdapter.getFilter().filter(newText);
return true;
}
#Override
public boolean onQueryTextSubmit(final String query)
{
return super.onQueryTextSubmit(query);
}
});
else
{
searchView=new EditText(this);
searchView.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
((EditText)searchView).setHint(R.string.search);
((EditText)searchView).addTextChangedListener(new TextWatcher()
{
String curretTextToFilter =null;
#Override
public void onTextChanged(final CharSequence newText,final int start,final int before,final int count)
{
if(newText==curretTextToFilter)
return;
curretTextToFilter=newText.toString();
_listAdapter.getFilter().filter(curretTextToFilter==null||curretTextToFilter.length()==0 ? null : curretTextToFilter);
}
#Override
public void beforeTextChanged(final CharSequence s,final int start,final int count,final int after)
{}
#Override
public void afterTextChanged(final Editable s)
{}
});
}
final View finalSearchView=searchView;
_searchMenuItem.setOnActionExpandListener(new OnActionExpandListener()
{
#Override
public boolean onMenuItemActionExpand(final MenuItem item)
{
if(finalSearchView instanceof EditText)
{
final InputMethodManager m=(InputMethodManager)getSystemService(Context.INPUT_METHOD_SERVICE);
finalSearchView.requestFocus();
if(m!=null)
m.toggleSoftInput(0,InputMethodManager.SHOW_IMPLICIT);
}
return true;
}
#Override
public boolean onMenuItemActionCollapse(final MenuItem item)
{
if(finalSearchView instanceof EditText)
((EditText)finalSearchView).setText(null);
else _listAdapter.getFilter().filter(null);
return true;
}
});
_searchMenuItem.setActionView(searchView);
//
return true;
}
#Override
public boolean onKeyUp(final int keyCode,final KeyEvent event)
{
if(keyCode==KeyEvent.KEYCODE_SEARCH)
{
_searchMenuItem.expandActionView();
return true;
}
return super.onKeyUp(keyCode,event);
}
Except for the "X" button, I think the rest can be done using a library with a theme, called HoloEverywhere.

Making custom search suggestions in ActionBarSherlock search bar

This is how I do my basic search using the ActionBar Search widget. This is obviously the easy way where the suggestions are provided in a listView in the layout. But I want the suggestions inside the search box itself. Though it was possible to do it in a normal search box, how do I do the same using Actionbar Search box.
public boolean onCreateOptionsMenu(com.actionbarsherlock.view.Menu menu) {
menu.add(0, 1, 1,"Search").setIcon(R.drawable.ic_search_inverse).setActionView(R.layout.collapsible_edittext).setShowAsAction(MenuItem.SHOW_AS_ACTION_IF_ROOM | MenuItem.SHOW_AS_ACTION_COLLAPSE_ACTION_VIEW);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(com.actionbarsherlock.view.MenuItem item) {
switch (item.getItemId()) {
case 1:
search = (AutoCompleteTextView) item.getActionView();
search.addTextChangedListener(filterTextWatcher);
search.requestFocus();
InputMethodManager imm = (InputMethodManager) getSystemService(Context.INPUT_METHOD_SERVICE);
imm.toggleSoftInput(InputMethodManager.SHOW_FORCED, 0);
return true;
}
return false;
}
private TextWatcher filterTextWatcher = new TextWatcher() {
public void afterTextChanged(Editable s) {
}
public void beforeTextChanged(CharSequence s, int start, int count, int after) {
}
public void onTextChanged(CharSequence s, int start, int before, int count) {
// your search logic here
doGeoSearch(String.valueOf(s));
}
};
public void doGeoSearch(String query){
Geocoder geocoder;
ArrayList<Address> addresses;
ArrayList<String> address = new ArrayList<String>() ;
geocoder = new Geocoder(this, Locale.getDefault());
try {
addresses = (ArrayList<Address>) geocoder.getFromLocationName(query, 6);
Log.d("Address",String.valueOf(addresses));
for(int i = 0;i<addresses.size();i++)
{
String addr = new String();
addr.concat(addresses.get(i).getAddressLine(0));
addr.concat(addresses.get(i).getAddressLine(1));
addr = addresses.get(i).getAddressLine(0) + addresses.get(i).getLocality() + addresses.get(i).getAdminArea();
//addr.concat(addresses.get(i).getAddressLine(2));
Log.d("addr",addr);
address.add(addr);
}
SearchAddressAdapater addressList = new SearchAddressAdapater(getApplicationContext(),R.layout.search_list,addresses, LocationActivity.this);
//addressView.setAdapter(addressList);
//ListView addressListView = new ListView();
} catch (IOException e) {
// TODO Auto-generated catch block
e.printStackTrace();
}
}
You can add a search widget to your ActionBar Sherlock, the search dialog has this functionality and it is very simple to implement as it is a simple expandable action item.
This tutorial will show you how to do everything you need with the search widget including search suggestions
Even though the SearchView was implemented and works, the search suggestions work on newer devices, but don't work on older devices like Gingerbread. Here's an issue:
https://github.com/JakeWharton/ActionBarSherlock/issues/659

android paste event

Is there a way to catch the paste event in my application? I must do something when I click long on an editText and select Paste from context menu. Thanks
Create menu.xml with position 'paste'
Register contextMenu to your EditText
EditText et=(EditText)findViewById(R.id.et);
registerForContextMenu(et);
Create contextMenu
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu, menu);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
menu.setHeaderTitle("title");
}
Create method menu onClick
#Override
public boolean onContextItemSelected(MenuItem item) {
AdapterContextMenuInfo info = (AdapterContextMenuInfo)item.getMenuInfo();
switch (item.getItemId()) {
case R.id.paste:
break;
}
return true;
}
You should implement a TextWatcher listener on the control that receives the paste action.
The TextWatcher class provides methods to handle the OnChange, BeforeChange and AfterChange of any Editable. For instance:
private void pasteEventHandler() {
((EditText)findViewById(R.id.txtOutput))
.addTextChangedListener(new TextWatcher() {
public void afterTextChanged(Editable s) {
Log.d(TAG, "Text changed, refreshing view.");
refreshView();
}
public void beforeTextChanged(CharSequence s, int start,
int count, int after) {
}
public void onTextChanged(CharSequence s, int start,
int before, int count) {
}
});
}
Below is code where you can override actionbar copy/Paste etc.
public class MainActivity extends Activity {
EditText editText;
private ClipboardManager myClipboard;
private ClipData myClip;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
editText = (EditText) findViewById(R.id.editText3);
myClipboard = (ClipboardManager) getSystemService(CLIPBOARD_SERVICE);
editText = (EditText) findViewById(R.id.editText3);
editText.setCustomSelectionActionModeCallback(new Callback() {
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case android.R.id.copy:
int min = 0;
int max = editText.getText().length();
if (editText.isFocused()) {
final int selStart = editText.getSelectionStart();
final int selEnd = editText.getSelectionEnd();
min = Math.max(0, Math.min(selStart, selEnd));
max = Math.max(0, Math.max(selStart, selEnd));
}
// Perform your definition lookup with the selected text
final CharSequence selectedText = editText.getText()
.subSequence(min, max);
String text = selectedText.toString();
myClip = ClipData.newPlainText("text", text);
myClipboard.setPrimaryClip(myClip);
Toast.makeText(getApplicationContext(), "Text Copied",
Toast.LENGTH_SHORT).show();
// Finish and close the ActionMode
mode.finish();
return true;
case android.R.id.cut:
// add your custom code to get cut functionality according
// to your requirement
return true;
case android.R.id.paste:
// add your custom code to get paste functionality according
// to your requirement
return true;
default:
break;
}
return false;
}
});
}
}
You can set Listener Class:
public interface GoEditTextListener {
void onUpdate();
}
Сreate self class for EditText:
public class GoEditText extends EditText
{
ArrayList<GoEditTextListener> listeners;
public GoEditText(Context context)
{
super(context);
listeners = new ArrayList<>();
}
public GoEditText(Context context, AttributeSet attrs)
{
super(context, attrs);
listeners = new ArrayList<>();
}
public GoEditText(Context context, AttributeSet attrs, int defStyle)
{
super(context, attrs, defStyle);
listeners = new ArrayList<>();
}
public void addListener(GoEditTextListener listener) {
try {
listeners.add(listener);
} catch (NullPointerException e) {
e.printStackTrace();
}
}
/**
* Here you can catch paste, copy and cut events
*/
#Override
public boolean onTextContextMenuItem(int id) {
boolean consumed = super.onTextContextMenuItem(id);
switch (id){
case android.R.id.cut:
onTextCut();
break;
case android.R.id.paste:
onTextPaste();
break;
case android.R.id.copy:
onTextCopy();
}
return consumed;
}
public void onTextCut(){
}
public void onTextCopy(){
}
/**
* adding listener for Paste for example
*/
public void onTextPaste(){
for (GoEditTextListener listener : listeners) {
listener.onUpdate();
}
}
}
xml:
<com.yourname.project.GoEditText
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/editText1"/>
And in your activity:
private GoEditText editText1;
editText1 = (GoEditText) findViewById(R.id.editText1);
editText1.addListener(new GoEditTextListener() {
#Override
public void onUpdate() {
//here do what you want when text Pasted
}
});
You could use this code that I've create recently
setOnReceiveContentListener(editText, arrayOf("text/*"),
OnReceiveContentListener { view, payload ->
if(view == editText && payload.source == ContentInfoCompat.SOURCE_CLIPBOARD && payload.clip.description.hasMimeType("text/*")) {
var t=""
for (i in 0 until payload.clip.itemCount) {
t += payload.clip.getItemAt(i).text
}
//do what ever you want to do with the text and set it to editText
editText.setText(t)
return#OnReceiveContentListener null
} else
return#OnReceiveContentListener payload
}
)
return the payload as it i, if not text and coming from clipboard to avoid any unintended intercepting
Got callback of paste event in onActionItemClicked(mode:ActionMode, item:MenuItem)
if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.M) {
editText.customInsertionActionModeCallback = object : ActionMode.Callback {
override fun onActionItemClicked(mode: ActionMode?, item: MenuItem?): Boolean {
Log.e("ActionMode", "::ItemClicked")
if(item?.groupId == android.R.id.paste){
Log.e("ActionMode", "::Paste::ItemClicked")
}
return true
}
override fun onCreateActionMode(mode: ActionMode?, menu: Menu?): Boolean {
Log.e("ActionMode", "::Created")
return true
}
override fun onPrepareActionMode(mode: ActionMode?, menu: Menu?): Boolean {
Log.e("ActionMode", "::Prepared")
return true
}
override fun onDestroyActionMode(mode: ActionMode?) {
Log.e("ActionMode", "::Destroyed")
}
}
}

Categories

Resources