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")
}
}
}
Related
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!
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());
}
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.
How to set null validation in edittextpreference dialog so that if it is null, the user should not be able to click ok and some message should be displayed in the dialog itself. I have been trying to find it for a long time but no success....
edttxtpref = (EditTextPreference) getPreferenceScreen().findPreference(
"edttxtkey");
edttxtpref.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(
android.preference.Preference preference, Object newValue) {
if (newValue.toString().trim().equals("")) {
Toast.makeText(getActivity(), "Username can not be empty",
Toast.LENGTH_LONG).show();
return false;
}
return true;
}
});
This way the validation is done and if we want to display the message in dialog itself then a custom dialog has to be created as already told by Phil.
I think what you are looking for is this. You are using the predefined PreferenceDialog (with EditText) and want to check if the Text is null. According to my knowledge, the "text" in this case is the changedPreference, therefore you can go with this:
Simply use an onPreferenceChangedListener for that.
yourPreference.setOnPreferenceChangeListener(new OnPreferenceChangeListener() {
#Override
public boolean onPreferenceChange(Preference preference, Object changedValue) {
if(changedValue == null) {
// handle it being null
return false;
} else {
return true;
}
}
});
For more advanced requirements, I would recommend that you implement your own Dialog and inside it, do whatever you desire. You can make that happen by defining a Preference list entry in .xml and then spawn the Dialog upon clicking on it.
Preference yourCustomPref = (Preference) findPreference("yourPref");
yourCustomPref.setOnPreferenceClickListener(new OnPreferenceClickListener() {
public boolean onPreferenceClick(Preference preference) {
// spawn your dialog here
return true;
}
});
This is how you could implement your custom EditText Dialog:
public Builder buildDialog(final Context c) {
AlertDialog.Builder builder = new AlertDialog.Builder(c);
builder.setTitle("EditText Dialog");
builder.setMessage("Enter text:");
LinearLayout llV = new LinearLayout(c);
llV.setOrientation(1); // 1 = vertical
final EditText patName = new EditText(c);
patName.setHint("Enter text...");
LinearLayout.LayoutParams lp = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1f);
lp.bottomMargin = 20;
lp.rightMargin = 30;
lp.leftMargin = 15;
patName.setLayoutParams(lp);
llV.addView(patName);
builder.setView(llV);
builder.setPositiveButton("Save", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
if(patName.getText().toString().length() > 0) {
} else {
}
}
});
builder.setNegativeButton("Cancel", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.dismiss();
}
});
return builder;
}
And then call it like this:
buildDialog(yourcontext).show();
When edittext is null then ok button will be disabled and as soon as the text is entered it will be enabled::
public class CustomEditTextPreference extends EditTextPreference implements
OnClickListener {
public CustomEditTextPreference(Context ctx, AttributeSet attrs, int defStyle)
{
super(ctx, attrs, defStyle);
}
public CustomEditTextPreference(Context ctx, AttributeSet attrs)
{
super(ctx, attrs);
}
private class EditTextWatcher implements TextWatcher
{
#Override
public void onTextChanged(CharSequence s, int start, int before, int count){}
#Override
public void beforeTextChanged(CharSequence s, int start, int before, int count){}
#Override
public void afterTextChanged(Editable s)
{
onEditTextChanged();
}
}
EditTextWatcher m_watcher = new EditTextWatcher();
/**
* Return true in order to enable positive button or false to disable it.
*/
protected boolean onCheckValue(String value)
{
if (value.trim().equals(""))
{
return false;
}
return true;
}
protected void onEditTextChanged()
{
boolean enable = onCheckValue(getEditText().getText().toString());
Dialog dlg = getDialog();
if(dlg instanceof AlertDialog)
{
AlertDialog alertDlg = (AlertDialog)dlg;
Button btn = alertDlg.getButton(AlertDialog.BUTTON_POSITIVE);
btn.setEnabled(enable);
}
}
#Override
protected void showDialog(Bundle state)
{
super.showDialog(state);
getEditText().removeTextChangedListener(m_watcher);
getEditText().addTextChangedListener(m_watcher);
onEditTextChanged();
}
}
How to modify the simple_list_item_multiple_choice with Image at the left corner. Please help me. I tried This example. But any possible way to use the simple_list_item_multiple_choice to do the same thing?
Please help me
Edit (Required format)
Your Question is Not showing exactly what are you want? Please clarify it and see this example may be it help you. Custom ListView
multiple selection
I guess you want a ListView with an ImageView in the left corner, CheckBox and a TextView in each row. If that is the case , then...No, you cannot use the simple_list_item_multiple_choice. You will have to use a BaseAdapter to achieve this.
For your requirement you can tweak the example you have used and add a
ImageView, CheckBox and a TextView to your xml for each row in ListView and populate them in the getView() of the adapter using a LayoutInflater
Try the following code, it might help you.
public class ActionModeDemo extends ListActivity {
private static final String[] items=
{ "lorem", "ipsum", "dolor", "sit", "amet", "consectetuer",
"adipiscing", "elit", "morbi", "vel", "ligula", "vitae",
"arcu", "aliquet", "mollis", "etiam", "vel", "erat",
"placerat", "ante", "porttitor", "sodales", "pellentesque",
"augue", "purus" };
private ArrayList<String> words=null;
#Override
public void onCreate(Bundle icicle) {
super.onCreate(icicle);
initAdapter();
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView()
.setMultiChoiceModeListener(new HCMultiChoiceModeListener(this,
getListView()));
}
else {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
registerForContextMenu(getListView());
}
}
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
l.setItemChecked(position, true);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
new MenuInflater(this).inflate(R.menu.option, menu);
EditText add=null;
if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.HONEYCOMB) {
View v=menu.findItem(R.id.add).getActionView();
if (v!=null) {
add=(EditText)v.findViewById(R.id.title);
}
}
if (add!=null) {
add.setOnEditorActionListener(onSearch);
}
return(super.onCreateOptionsMenu(menu));
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
new MenuInflater(this).inflate(R.menu.context, menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.add:
add();
return(true);
case R.id.reset:
initAdapter();
return(true);
case R.id.about:
case android.R.id.home:
Toast
.makeText(this, "Action Bar Sample App", Toast.LENGTH_LONG)
.show();
return(true);
}
return(super.onOptionsItemSelected(item));
}
#Override
public boolean onContextItemSelected(MenuItem item) {
boolean result=performActions(item);
if (!result) {
result=super.onContextItemSelected(item);
}
return(result);
}
#SuppressWarnings("unchecked")
public boolean performActions(MenuItem item) {
ArrayAdapter<String> adapter=(ArrayAdapter<String>)getListAdapter();
SparseBooleanArray checked=getListView().getCheckedItemPositions();
switch (item.getItemId()) {
case R.id.cap:
for (int i=0;i<checked.size();i++) {
if (checked.valueAt(i)) {
int position=checked.keyAt(i);
String word=words.get(position);
word=word.toUpperCase();
adapter.remove(words.get(position));
adapter.insert(word, position);
}
}
return(true);
case R.id.remove:
ArrayList<Integer> positions=new ArrayList<Integer>();
for (int i=0;i<checked.size();i++) {
if (checked.valueAt(i)) {
positions.add(checked.keyAt(i));
}
}
Collections.sort(positions, Collections.reverseOrder());
for (int position : positions) {
adapter.remove(words.get(position));
}
getListView().clearChoices();
return(true);
}
return(false);
}
private void initAdapter() {
words=new ArrayList<String>();
for (String s : items) {
words.add(s);
}
setListAdapter(new ArrayAdapter<String>(
this,
android.R.layout.simple_list_item_checked,
words));
}
private void add() {
final View addView=getLayoutInflater().inflate(R.layout.add, null);
new AlertDialog.Builder(this)
.setTitle("Add a Word")
.setView(addView)
.setPositiveButton(
"OK",
new DialogInterface.OnClickListener() {
public void onClick(
DialogInterface dialog,
int whichButton) {
addWord((TextView)addView
.findViewById(R.id.title));
}
})
.setNegativeButton("Cancel", null)
.show();
}
#SuppressWarnings("unchecked")
private void addWord(TextView title) {
ArrayAdapter<String> adapter=(ArrayAdapter<String>)getListAdapter();
adapter.add(title.getText().toString());
}
private TextView.OnEditorActionListener onSearch=
new TextView.OnEditorActionListener() {
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
if (event==null||event.getAction()==KeyEvent.ACTION_UP) {
addWord(v);
InputMethodManager imm=
(InputMethodManager)getSystemService(INPUT_METHOD_SERVICE);
imm.hideSoftInputFromWindow(v.getWindowToken(), 0);
}
return(true);
}
};
}
public class HCMultiChoiceModeListener implements AbsListView.MultiChoiceModeListener {
ActionModeDemo host;
ActionMode activeMode;
ListView lv;
HCMultiChoiceModeListener(ActionModeDemo host, ListView lv) {
this.host=host;
this.lv=lv;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater=host.getMenuInflater();
inflater.inflate(R.menu.context, menu);
mode.setTitle(R.string.context_title);
mode.setSubtitle("(1)");
activeMode=mode;
return(true);
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return(false);
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
boolean result=host.performActions(item);
updateSubtitle(activeMode);
return(result);
}
#Override
public void onDestroyActionMode(ActionMode mode) {
activeMode=null;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
updateSubtitle(mode);
}
private void updateSubtitle(ActionMode mode) {
mode.setSubtitle("("+lv.getCheckedItemCount()+")");
}
}
Try this below Code Snippet.
Activity_name.this.runOnUiThread(new Runnable() {
#Override
public void run() {
list = (ArrayList<Map<String, String>>) result;
this.adapter.setList(list);
this.adapter.notifyDataSetChanged();
}
});