Android Webview: Override Contextual Action Bar - android

I am trying to override a contextual action bar in Android Webview. When I long click on a selected word, the custom action bar is displayed. However, when I click on the action bar button, nothing happens.
It seems like the onContextItemSelected() function is not called. This is my code:
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.dictionary);
mWebView = (WebView) findViewById(R.id.wv);
}
#Override
public boolean onContextItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.save_word:
Toast.makeText(CheckDictionary.this,"Save Word Meaning Successfully",Toast.LENGTH_LONG).show();
break;
default:
break;
}
if (mActionMode != null) {
mActionMode.finish();
}
return super.onContextItemSelected(item);
}
#Override
public void onActionModeStarted(ActionMode mode) {
if (mActionMode == null) {
mActionMode = mode;
mode.setTitle("Save Word Meaning");
Menu menu = mode.getMenu();
menu.clear();
mode.getMenuInflater().inflate(R.menu.dictionary_menu, menu);
}
super.onActionModeStarted(mode);
}
#Override
public void onActionModeFinished(ActionMode mode) {
mActionMode = null;
super.onActionModeFinished(mode);
}
}

I am doing this job on my old projects like this:
private String[] data = {"1", "2", "3", "4", "5", "6", "7", "8", "9","10"};
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new SelectionAdapter(this,
R.layout.row_list_item, R.id.textView1, data);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#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
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
mode.finish();
}
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " selected");
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<? arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return false;
}
});
}
private class SelectionAdapter extends ArrayAdapter<String {
private HashMap<Integer, Boolean mSelection = new HashMap<Integer, Boolean();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(getResources().getColor(android.R.color.background_light));
if (mSelection.get(position) != null) {
v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light);
}
return v;
}
}
You can make changes in this code according to your needs...

try below steps
public class MyWebView extends WebView {
MyActivity theListener;
Context context;
GestureDetector gd;
public MyWebView(Context context, AttributeSet attributes) {
super(context, attributes);
this.context = context;
gd = new GestureDetector(context, sogl);
}
// This is new
public void setListener(MyActivity l) {
theListener = l;
}
#Override
public boolean onTouchEvent(MotionEvent event) {
return gd.onTouchEvent(event);
}
GestureDetector.SimpleOnGestureListener sogl =
new GestureDetector.SimpleOnGestureListener() {
public boolean onDown(MotionEvent event) {
return true;
}
public void onLongPress(MotionEvent event) {
theListener.onLongClick(MyWebView.this);
}
};
}
and in activity
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.layout);
MyWebView mwv = (MyWebView) findViewById(R.id.mwv);
registerForContextMenu(mwv);
}
public boolean onLongClick(View v) {
openContextMenu(v);
return true;
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenu.ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.context, menu);
}

Related

Delete from database via ViewList MultiSelection

I have the next code.
public class ListAnotaciones extends ListActivity {
AnotacionesOpenHelper openHelper = AnotacionesOpenHelper.getAnotaciones(this);
SQLiteDatabase bd;
Cursor cursor;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelper.getReadableDatabase();
cursor = bd.rawQuery("select * from anotaciones", null);
final ArrayList<Cursor> lista = new ArrayList<Cursor>();
try {
String [] from = {"titulo", "fecha"};
int [] to = {R.id.anotacionesTexto, R.id.anotacionesFecha};
final SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.anotacion, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
int seleccion = getListView().getCheckedItemCount();
boolean borrado = false;
if(checked){
lista.add((Cursor)getListView().getItemAtPosition(position));
lista.get(0).moveToFirst();
Toast.makeText(getApplicationContext(),lista.get(0).getString(0),Toast.LENGTH_SHORT).show();
}else{
/*
SQLiteCursor seleccionado = (SQLiteCursor)getListView().getItemAtPosition(position);
for(int i = 0;i < lista.size();i++){
if(lista.get(i).getString(0).equals(seleccionado.getString(0))){
lista.remove(i);
borrado = true;
break;
}
}
*/
}
mode.setTitle(seleccion + " Notas Seleccionadas");
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.ctx_borrar,menu); //Inflamos el menú creado como XML en 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.CtxLblBorrar:
/*
for(int i = 0 ; i < lista.size();i++){
Toast.makeText(getApplicationContext(),lista.get(i).getString(0),Toast.LENGTH_SHORT).show();
bd.delete("anotaciones","_id = " + lista.get(i).getString(0),null);
}
*/
while(lista.get(0).moveToNext()){
bd.delete("anotaciones","_id = " + lista.get(0).getString(0),null);
}
adapter.notifyDataSetChanged();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
}
);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
/*#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}*/
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.CtxLblBorrar:
Toast.makeText(getApplicationContext(),"Se ha pulsado Borrar - " + getListView().getCheckedItemCount(),Toast.LENGTH_SHORT).show();
return true;
default:
Toast.makeText(getApplicationContext(),"OPCION NO PROGRAMADA",Toast.LENGTH_SHORT).show();
return super.onOptionsItemSelected(item);
}
}
#Override
public void onCreateContextMenu(ContextMenu menu, View v, ContextMenu.ContextMenuInfo menuInfo){
super.onCreateContextMenu(menu, v, menuInfo);
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.ctx_borrar, menu);
}
}
I'm trying to delete from the database and then update the ListView. I've seen several solutions here but I can't adapt the solutions to my code (I'm pretty new with android).
More specifically, I don't know how to "save" the options than I need to delete.
If you need more code please say so.
SOLVED
I'm so sorry, I'm a little blind,
It's the code for my question
public class ListAnotaciones extends ListActivity {
AnotacionesOpenHelper openHelper = AnotacionesOpenHelper.getAnotaciones(this);
SQLiteDatabase bd;
Cursor cursor;
Context contexto = this;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
bd = openHelper.getWritableDatabase();
cursor = bd.rawQuery("select * from anotaciones", null);
final ArrayList<Long> borrar = new ArrayList<Long>();
try {
String [] from = {"titulo", "fecha", "texto"};
int [] to = {R.id.anotacionesTitulo, R.id.anotacionesFecha,R.id.anotacionesTexto};
SimpleCursorAdapter adapter = new SimpleCursorAdapter(this, R.layout.anotacion, cursor, from, to, CursorAdapter.FLAG_REGISTER_CONTENT_OBSERVER);
setListAdapter(adapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(
new AbsListView.MultiChoiceModeListener(){
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
Toast.makeText(getApplicationContext(),Long.toString(id),Toast.LENGTH_SHORT).show();
if(checked){
borrar.add(id);
}else{
for(int i = 0; i < borrar.size();i++){
if(borrar.get(i) == id){
borrar.remove(i);
}
}
Toast.makeText(getApplicationContext(),"Deseleccionado",Toast.LENGTH_SHORT).show();
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.ctx_borrar,menu); //Inflamos el menú creado como XML en Menu
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()){
case R.id.CtxLblBorrar:
Toast.makeText(getApplicationContext(),"Se ha pulsado Borrar",Toast.LENGTH_SHORT).show();
for(int i = 0 ; i < borrar.size();i++){
bd.delete("anotaciones","_id=" + borrar.get(i),null);
}
return true;
default:
return false;
}
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
}
);
} catch (IllegalArgumentException e) {
e.printStackTrace();
}
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.anotaciones, menu);
return true;
}
}
Thanks you anyway for the solves

notifyDataSetChanged() not refreshing listview

This is my adapter:
public class Conversa extends BaseAdapter {
private Context context;
private ArrayList<String> log;
private String target;
public Conversa(Context context, String target) {
this.context = context;
this.target = target;
log = new ArrayList<String>();
}
#Override
public int getCount() {
return log.size();
}
#Override
public Object getItem(int pos) {
return log.get(pos);
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.msg_layout, parent, false);
}
TextView msg = (TextView) convertView.findViewById(R.id.msg);
msg.setText(log.get(pos));
return convertView;
}
public ArrayList<String> getLog() {
return log;
}
public String getTarget() {
return target;
}
public void setTarget(String target) {
this.target = target;
}
public void addMessage(String msg) {
log.add(msg);
notifyDataSetChanged();
}
}
And this is my Fragment, it haves a listview that is not refreshed when the Conversa.addMessage() is called.
public class ChatFragment extends Fragment {
private String target;
private ListView listview;
private EditText edittext;
private Conversa conversa;
private MainActivity activity;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
target = getArguments().getString(IRCService.EXTRA_TARGET);
activity = (MainActivity) getActivity();
conversa = activity.service.getConversa(target);
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
setHasOptionsMenu(true);
View view;
view = inflater.inflate(R.layout.chat_layout, container, false);
edittext = (EditText) view.findViewById(R.id.chatinput);
listview = (ListView) view.findViewById(R.id.chatlist);
listview.setAdapter(conversa);
// EM CASO DE RETORNO DO SERVICE EM BACKGROUND, ROLAR A LISTA ATEH O FIM
if (!conversa.getLog().isEmpty()) {
scrollMyListViewToBottom();
}
// LISTENER QUE RECEBERA O "ENVIAR" DO TECLADO DO ANDROID
edittext.setOnEditorActionListener(new OnEditorActionListener() {
#Override
public boolean onEditorAction(TextView v, int actionId,
KeyEvent event) {
boolean handled = false;
if (actionId == EditorInfo.IME_ACTION_SEND) {
// ESCONDE O TECLADO APOS ENVIAR
InputMethodManager in = (InputMethodManager) getActivity()
.getSystemService(Context.INPUT_METHOD_SERVICE);
in.hideSoftInputFromWindow(
edittext.getApplicationWindowToken(),
InputMethodManager.HIDE_NOT_ALWAYS);
sendMessage(target, edittext.getText().toString());
// ALTERA O FLAG
handled = true;
}
return handled;
}
});
return view;
}
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
if (target.equals(IRCService.CANAL)) {
inflater.inflate(R.menu.canal_menu, menu);
} else {
inflater.inflate(R.menu.pvt_menu, menu);
}
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.menu_closepvt:
activity.removePVTTab(conversa.getTarget());
return true;
case R.id.menu_desconectar:
activity.service.IRCdisconnect();
return true;
case R.id.menu_mudarnick:
// TODO IMPLEMENTAR MUDANÇA DE NICK
return true;
}
return false;
}
public void sendMessage(String target, String msg) {
activity.service.sendMessage(target, msg);
// APAGA O EDITTEXT
edittext.setText("");
}
private void scrollMyListViewToBottom() {
listview.post(new Runnable() {
#Override
public void run() {
// Select the last row so it will scroll into view...
listview.setSelection(conversa.getCount() - 1);
}
});
}
public void setQuote(String nick) {
((MainActivity) getActivity()).drawerlayout.closeDrawers();
edittext.setText(nick + ": ");
edittext.requestFocus();
}
}
If i receive a chat message, it dont appears on list, despite the message be in the log. When i touch the edittext to write a message, it refreshes the view and the message appears.
I wanna it appears as soon as it comes.
Please help me.
Remove the
public void addMessage(String msg) {
log.add(msg);
notifyDataSetChanged();
and use it in your main Activity:
Conversa.log.add(msg);
notifyDataSetChanged();

Android delete selected item using contextual actionbar

So far, I have managed to follow this tutorial and run it successfully. But what I wanna do now is to actually delete selected items on my listview. This is the code I'm using:
private String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten"};
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new SelectionAdapter(this,
R.layout.row_list_item, R.id.textView1, data);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#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
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
mode.finish();
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " selected");
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return false;
}
});
}
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red
}
return v;
}
}
Question is how do I delete the selected item/s? I can't figure it out and if anyone of you knows this and can help, I'd gladly appreciate it. Thanks.
In your code instead of using string [] data you can use ArrayList<String> data since it is dynamically sized array where the object is actually removed and the list (array) size is adjusted accordingly. With this change you can use following method.
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
List<Integer> keyList = new ArrayList<Integer>(noteAdptr.getCurrentCheckedPosition());
Collections.sort(keyList, new Comparator<Integer>() {
#Override
public int compare(Integer lhs, Integer rhs) {
return lhs.compareTo(rhs);
}
});
Collections.reverse(keyList);
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
for (Integer i:keyList){
Log.e("", "items selected is : "+i);
data.remove((int)i);
}
mAdapter .notifyDataSetChanged();
mAdapter.clearSelection();
mode.finish();
}
return true;
}
Hope this helps
You can set a OnLongClickListener on the items in the ListView that just gets the item that is long pressed.
Afterwards you can reference/remove that object in your OnActionItemClicked.
I am not sure if you have already solved your problem, but here is what worked for me:
Create a private (or public) variable in your class: private int selectedPosition;
In your onItemLongClick() method (as far as I see that's the one, where you are selecting an item), put:
selectedPosition = position;
in OnActionItemClicked() you can get your adapter and do this:
MyAdapter adapter = (MyAdapter) this.getAdapter();
adapter.remove(adapter.getItem(selectedPosition);
adapter.notifyDataSetChanged();
That way you passed the position of the selected item to your adapter.
Hope that helps!
You have to code the functionality yourself: in the onActionItemClicked, you have to code the logic that will erase selected items from your ArrayList.
Don't forget to call notifyDatasetChanged() on your adapter after that... ;-)

Android delete selected items listview using contextmenu actionbar

So far this is what I've tried:
private String[] data = {"One", "Two", "Three", "Four", "Five", "Six", "Seven", "Eight", "Nine","Ten"};
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mAdapter = new SelectionAdapter(this,
R.layout.row_list_item, R.id.textView1, data);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#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
mAdapter.clearSelection();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
// TODO app mAdapter.removeSelection(position);
mode.finish();
}
return true;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// TODO Auto-generated method stub
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " selected");
}
});
getListView().setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> arg0, View arg1,
int position, long arg3) {
// TODO Auto-generated method stub
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return false;
}
});
}
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, String[] objects) {
super(context, resource, textViewResourceId, objects);
}
public void setNewSelection(int position, boolean value) {
mSelection.put(position, value);
notifyDataSetChanged();
}
public boolean isPositionChecked(int position) {
Boolean result = mSelection.get(position);
return result == null ? false : result;
}
public Set<Integer> getCurrentCheckedPosition() {
return mSelection.keySet();
}
public void removeSelection(int position) {
mSelection.remove(position);
notifyDataSetChanged();
}
public void clearSelection() {
mSelection = new HashMap<Integer, Boolean>();
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View v = super.getView(position, convertView, parent);//let the adapter handle setting up the row views
v.setBackgroundColor(getResources().getColor(android.R.color.background_light)); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(getResources().getColor(android.R.color.holo_blue_light));// this is a selected position so make it red
}
return v;
}
}
But I need to know how to get the selected items and put it inside OnActionItemClicked like what I've tried here:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
mAdapter.clearSelection();
// TODO app mAdapter.removeSelection(position);
mode.finish();
}
return true;
}
I commented out mAdapter.removeSelection() because I don't know what to put inside.
Any ideas? help is pretty much appreciated. Thanks.
Their are multiple things you could do.. The easiest way i think is as follows:
It doesn't work because the onActionItemClicked expects one item. But you select multiple items.
The easiest way is to create a loop in which you handle the normal procedure the onActionItemClicked expects
ListView mListView = getListView();
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// TODO Auto-generated method stub
switch (item.getItemId()) {
case R.id.item_delete:
nr = 0;
Long[] longConverts = new Long(mListView.getCheckedItemIds());
private List<Long> itemids = new ArrayList<Long>(Arrays.asList(longConverts));
for(int i=0;i<itemids.size();i++){
mListView.remove(itemids.get(i));
mAdapter.clearSelection();
// TODO app mAdapter.removeSelection(position);
mode.finish();
}
return true;
}
I think this should work.. It retrieves the selected items first from the ListView then put them in a array and loops over that array to remove the items one by one..
I hope this works for you

How to implement search functionality?

I am having a grid view and I have to add search functionality in the action bar.So that whatever i type to search,the items should come whatever i searched.Grid view is having image and text.I stuck in this very badly.I dont know how to implement it.I gone through android guide but I unable to get it.
Please suggest some easy way to do it.I need search like in watsaap application.
Any suggestion is appreciated.Thanks.
Here is my gridview code.
public class FragmentDeals extends Fragment implements Checkable{
private boolean mChecked;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View layout = inflater.inflate(R.layout.fragmentdeal,
(ViewGroup)
findViewById(R.id.layoutdeal));
//View view = inflater.inflate(R.layout.griddeal,null);
final GridView mGrid = (GridView) layout.findViewById(R.id.GridDeal);
mGrid.setAdapter(new DealAdapter());
mGrid.setChoiceMode(GridView.CHOICE_MODE_MULTIPLE_MODAL);
mGrid.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public boolean onActionItemClicked(ActionMode mode,
MenuItem item) {
// TODO Auto-generated method stub
return true;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.setTitle("Select Items");
mode.setSubtitle("One item selected");
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
//listView.setLongClickable(false);
int selectCount = mGrid.getCheckedItemCount();
switch (selectCount) {
case 1:
mode.setSubtitle("One item selected");
break;
default:
mode.setSubtitle("" + selectCount +"items selected");
break;
}
}
});
return layout;
// TODO Auto-generated method stub
}
#Override
public boolean isChecked() {
// TODO Auto-generated method stub
return mChecked;
}
#SuppressWarnings("deprecation")
#Override
public void setChecked(boolean checked) {
// TODO Auto-generated method stub
mChecked = checked;
layout.setBackgroundDrawable(checked ? getResources().getDrawable(
R.drawable.bground) : null);
}
#Override
public void toggle() {
// TODO Auto-generated method stub
setChecked(!mChecked);
}
}
private class DealAdapter extends BaseAdapter {
#Override
public int getCount() {
return mThumbIds1.length;
}
#Override
public Object getItem(int position) {
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
//CheckableLayout l;
View myView = convertView;
LayoutInflater inflater = (LayoutInflater)MainActivity.this.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
myView = inflater.inflate(R.layout.griddealitems, null);
// Add The Image!!!
ImageView iv = (ImageView)myView.findViewById(R.id.grid_deal_image);
iv.setImageResource(mThumbIds1[position]);
// Add The Text!!!
TextView tv = (TextView)myView.findViewById(R.id.grid_deal_text);
tv.setText(names1[position] );
return myView;
}
private Integer[] mThumbIds1= {
R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car,
R.drawable.car,R.drawable.car,R.drawable.car,R.drawable.car, R.drawable.car,
R.drawable.car, R.drawable.car,
R.drawable.car,R.drawable.car,R.drawable.car
};
private String[] names1={"ab","cd","ef","gh","ij","kl","mn","","","","","","",""};
}
I have never tried for search functionality with gridview. But i have done the same for list view. Please have a look on the following link to implement search functionality for listview
Search functionality with list view
http://www.androidbegin.com/tutorial/android-search-listview-using-filter/

Categories

Resources