Delete Multiple Selected Items in ListView (cab) in android - java

I want to delete multiple selected items (row) in my listview (Gmail style).
If I select (with longClick) a row, nothing happens.
I've found this code on internet, and i've tried to insert it in my project.
MainActivity
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(Lista.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode actionMode, MenuItem menu) {
switch (menu.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selectedItem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selectedItem);
}
}
actionMode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode actionMode, Menu menu) {
actionMode.getMenuInflater().inflate(R.menu.delete_menu, menu);
return false;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode actionMode, int position,
long arg2, boolean arg3) {
final int checkedOut = Lista.getCheckedItemCount();
actionMode.setTitle(checkedOut + " selezionato");
adapter.toggleSelection(position);
}
and this is the adapter
public class ListaAdapter extends ArrayAdapter<ListViewItem> {
private Context context;
private ArrayList<ListViewItem> items;
private SparseBooleanArray mSelectedItemsIds;
public ListaAdapter(Context context, int resourceId,
ArrayList<ListViewItem> items) {
super(context, resourceId, items);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.items = items;
}
private class ViewHolder {
ImageView imageView;
TextView txtTitle;
TextView txtSubTitle;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
if (convertView == null) {
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_view_item, null);
holder = new ViewHolder();
holder.txtTitle = (TextView) convertView
.findViewById(R.id.TitoloPrincipale);
holder.txtSubTitle = (TextView) convertView
.findViewById(R.id.Sottotitolo);
holder.imageView = (ImageView) convertView.findViewById(R.id.Image);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
ListViewItem list = getItem(position);
holder.txtTitle.setText(list.getNomeFarmaco());
holder.txtSubTitle.setText(list.getFasceOrarie());
holder.imageView.setImageResource(list.getIcon());
// convertView
// .setBackgroundColor(mSelectedItemsIds.get(position)
// : Color.TRANSPARENT);
return convertView;
}
public void remove(ListViewItem item) {
items.remove(item);
notifyDataSetChanged();
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
have you got any idea?
tks

That code has nothing to do with long-clicks. The only occurrence of "long" is for a long parameter to a method. :-)
This sample project demonstrates an action mode starting up based upon a long-click of a list row. The key is onItemLongClick():
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view,
int position, long id) {
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setItemChecked(position, true);
return(true);
}
Here (courtesy of registering the activity as the OnItemLongClickListener for the ListView), we toggle on CHOICE_MODE_MULTIPLE_MODAL and check the item that was long-clicked, thereby activating the action mode.

The major problem you have not setMultiChoiceModeListener for listview like below
(Plz, see carefully onCreateActionMode and the loop in onActionItemClicked)
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#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
mode.getMenuInflater().inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem menuItem) {
// TODO Auto-generated method stub
switch (menuItem.getItemId()) {
case R.id.mnDelete:
SparseBooleanArray sparseBooleanArray = listView.getCheckedItemPositions();
for(int i = sparseBooleanArray.size() -1; i >= 0; i--)
items.remove(sparseBooleanArray.keyAt(i));
adapter.notifyDataSetChanged();
mode.finish();
break;
default:
break;
}
return true;
}
});
}

I've solved. thank you all.
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_lista, container,
false);
Lista = (ListView) rootView.findViewById(R.id.Lista);
items = new ArrayList<ListViewItem>();
items = GetLists.GetRecordList(rootView.getContext());
adapter = new ListaAdapter(rootView.getContext(),
R.layout.list_view_item, items);
Lista.setAdapter(adapter);
Lista.setMultiChoiceModeListener(this);
Lista.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
return rootView;
}
#Override
public boolean onActionItemClicked(ActionMode arg0, MenuItem arg1) {
switch (arg1.getItemId()) {
case R.id.menu_delete:
SparseBooleanArray selected = adapter.getSelectedIds();
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
ListViewItem selecteditem = adapter.getItem(selected
.keyAt(i));
adapter.remove(selecteditem);
}
}
// Close CAB
arg0.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode arg0, Menu arg1) {
arg0.getMenuInflater().inflate(R.menu.delete_menu, arg1);
return true;
}
#Override
public void onDestroyActionMode(ActionMode arg0) {
adapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
return false;
}
#Override
public void onItemCheckedStateChanged(ActionMode arg0, int arg1, long arg2,
boolean arg3) {
final int checkedCount = Lista.getCheckedItemCount();
arg0.setTitle(checkedCount + " Selected");
adapter.toggleSelection(arg1);
}
}

Related

Getting value of each selected item using a contextual action bar

I am using a contextual action bar and wish to retrieve each value selected to pass to another activity after I click on the 'mail' button. How can I do this?e
Code for the CAB.
mAdapter = new SelectionAdapter(this, R.layout.activity_result, R.id.name, new String[] {TAG_NAME, TAG_ROOM_PRICE});
setListAdapter(mAdapter);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(android.view.ActionMode mode, Menu menu) {
nr = 0;
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.contextual_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(android.view.ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(android.view.ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.email:
}
return false;
}
#Override
public void onDestroyActionMode(android.view.ActionMode mode) {
mAdapter.clearSelection();
}
#Override
public void onItemCheckedStateChanged(android.view.ActionMode mode, int position, long id, boolean checked) {
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle("No: of resorts selected: " + nr);
}
});
lv.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id) {
//String name = ((TextView) view.findViewById(R.id.name)).getText().toString();
getListView().setItemChecked(position, !mAdapter.isPositionChecked(position));
return true;
}
});
Selection adapter class which is used to define the object mAdapter
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;
}
}
I wish to retrieve the String value of every selection that I make
I found the solution.
mAdapter.setNewSelection(position, checked);
String get_list = resortsList.get(position).get(TAG_NAME);
stringList.add(get_list);
And to remove the item selected when deselected:`int i;
for(i = 0 ; i < stringList.size(); i++){
if(stringList.get(i).equals(resortsList.get(position).get(TAG_NAME))){
stringList.remove(i);
Log.d("String List: ", stringList.toString());
break;
}
}`

Android: onItemCheckedStateChanged is called only once

Fragment class:
public class MultiFragmentListContent extends ListFragment
{
ListView listView;
ActionMode actionMode;
ArrayAdapter<String> arrayAdapter;
List<String> stringList;
Set<String> checkList;
AbsListView.MultiChoiceModeListener choiceModeListener = null;
#Override
public View onCreateView (LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
super.onCreateView(inflater,container,savedInstanceState);
View rootView = inflater.inflate(R.layout.fragment, container, false);
return rootView;
}
#Override
public void onActivityCreated(Bundle savedInstanceState)
{
super.onActivityCreated(savedInstanceState);
checkList = new HashSet<>();
stringList = new LinkedList<>();
stringList.add("A");
stringList.add("B");
stringList.add("C");
stringList.add("D");
stringList.add("E");
listView = getListView();
arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.string,stringList);
listView.setAdapter(arrayAdapter);
choiceModeListener = new AbsListView.MultiChoiceModeListener()
{
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked)
{
if(checked)
checkList.add(stringList.get(position));
else
checkList.remove(stringList.get(position));
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu)
{
actionMode = mode;
MenuInflater menuInflater = mode.getMenuInflater();
menuInflater.inflate(R.menu.contentmenu2,menu);
arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.checkbox,stringList);
listView.setAdapter(arrayAdapter);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return true;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item)
{
switch(item.getItemId())
{
case R.id.contextmenu2:
for(String k : checkList)
{
stringList.remove(k);
Log.i(k,k);
}
actionMode.finish();
break;
}
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode)
{
arrayAdapter = new ArrayAdapter<String>(getActivity(),R.layout.string,stringList);
listView.setAdapter(arrayAdapter);
checkList.removeAll(checkList);
}
};
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(choiceModeListener);
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener()
{
#Override
public boolean onItemLongClick(AdapterView<?> parent, View view, int position, long id)
{
listView.setMultiChoiceModeListener(choiceModeListener);
return true;
}
});
}
}
I noted that the method onItemCheckedStateChanged is called only once.
Before that method worked, I mean it was always called.
I tried to find on the web but I didn't find a solution.
I think that the problem is
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
but I don't know where to put it. If I put it in other places, the app crashes.
It's possible if you create one boolean value for your control in onItemCheckedStateChanged, the call always called, but will a have control.

Java Index out of bounds exception to delete multiple images

I am creating an android app in which the user can capture the images and these images are displayed in gridview.when the user wants to delete one or more images by touching the images i am getting an java index out of bounds exception.The example which i have seen has used the image adapter extending to a arrayadapter but i am using an image adapter which extends to base adapter. So i don't know because of it does the error occurs.
grid.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
final int checkedCount = grid.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
adapter.toggleSelection(position);
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.delete_mode, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode actionMode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = adapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
int selecteditem = (int) adapter
.getItem(selected.keyAt(i));
//Remove selected items following the ids
String imgPath = listOfImagesPath.get(selecteditem);
File file=new File(imgPath);
file.delete();
adapter.removeitem(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode actionMode) {
adapter.removeSelection();
}
});
Image adapter(which i have created):
public class ImageListAdapter extends BaseAdapter
{
private Context context;
private List<String> imgPic;
private SparseBooleanArray mSelectedItemsIds;
public ImageListAdapter(Context c, List<String> thePic)
{
context = c;
imgPic = thePic;
mSelectedItemsIds = new SparseBooleanArray();
}
public int getCount() {
if(imgPic != null)
return imgPic.size();
else
return 0;
}
//---returns the ID of an item---
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public void removeitem(int position){
imgPic.remove(position);
notifyDataSetChanged();
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
//---returns an ImageView view---
public View getView(int position, View convertView, ViewGroup parent)
{
ImageView imageView;
BitmapFactory.Options bfOptions=new BitmapFactory.Options();
bfOptions.inDither=false; //Disable Dithering mode
bfOptions.inPurgeable=true; //Tell to gc that whether it needs free memory, the Bitmap can be cleared
bfOptions.inInputShareable=true; //Which kind of reference will be used to recover the Bitmap data after being clear, when it will be used in the future
bfOptions.inTempStorage=new byte[32 * 1024];
if (convertView == null) {
imageView = new ImageView(context);
imageView.setLayoutParams(new GridView.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, ViewGroup.LayoutParams.MATCH_PARENT));
imageView.setPadding(0, 0, 0, 0);
} else {
imageView = (ImageView) convertView;
}
FileInputStream fs = null;
Bitmap bm;
try {
fs = new FileInputStream(new File(imgPic.get(position).toString()));
if(fs!=null) {
bm=BitmapFactory.decodeFileDescriptor(fs.getFD(), null, bfOptions);
imageView.setImageBitmap(bm);
imageView.setId(position);
imageView.setLayoutParams(new GridView.LayoutParams(200, 160));
}
} catch (IOException e) {
e.printStackTrace();
} finally{
if(fs!=null) {
try {
fs.close();
} catch (IOException e) {
e.printStackTrace();
}
}
}
return imageView;
}
}
Image adapter(the example which i saw for deleting multiple images in grid)
public class ListViewAdapter extends ArrayAdapter<WorldPopulation> {
// Declare Variables
Context context;
LayoutInflater inflater;
List<WorldPopulation> worldpopulationlist;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context, int resourceId,
List<WorldPopulation> worldpopulationlist) {
super(context, resourceId, worldpopulationlist);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.worldpopulationlist = worldpopulationlist;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView rank;
TextView country;
TextView population;
ImageView flag;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.rank = (TextView) view.findViewById(R.id.rank);
holder.country = (TextView) view.findViewById(R.id.country);
holder.population = (TextView) view.findViewById(R.id.population);
// Locate the ImageView in listview_item.xml
holder.flag = (ImageView) view.findViewById(R.id.flag);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews
holder.rank.setText(worldpopulationlist.get(position).getRank());
holder.country.setText(worldpopulationlist.get(position).getCountry());
holder.population.setText(worldpopulationlist.get(position)
.getPopulation());
// Capture position and set to the ImageView
holder.flag.setImageResource(worldpopulationlist.get(position)
.getFlag());
return view;
}
#Override
public void remove(WorldPopulation object) {
worldpopulationlist.remove(object);
notifyDataSetChanged();
}
public List<WorldPopulation> getWorldPopulation() {
return worldpopulationlist;
}
public void toggleSelection(int position) {
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection() {
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position, boolean value) {
if (value)
mSelectedItemsIds.put(position, value);
else
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
public int getSelectedCount() {
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
Error:
java.lang.IndexOutOfBoundsException: Invalid index 1, size is 0
at java.util.ArrayList.throwIndexOutOfBoundsException(ArrayList.java:255)
at java.util.ArrayList.remove(ArrayList.java:403)
at nidhinkumar.gridcam.Cam$ImageListAdapter.removeitem(Cam.java:360)
at nidhinkumar.gridcam.Cam$4.onActionItemClicked(Cam.java:200)
at android.widget.AbsListView$MultiChoiceModeWrapper.onActionItemClicked(AbsListView.java:6693)
at com.android.internal.policy.impl.PhoneWindow$DecorView$ActionModeCallbackWrapper.onActionItemClicked(PhoneWindow.java:3430)
at android.support.v7.view.SupportActionModeWrapper$CallbackWrapper.onActionItemClicked(SupportActionModeWrapper.java:168)
at android.support.v7.app.AppCompatDelegateImplV7$ActionModeCallbackWrapperV7.onActionItemClicked(AppCompatDelegateImplV7.java:1703)
at android.support.v7.app.AppCompatDelegateImplV7$ActionModeCallbackWrapperV7.onActionItemClicked(AppCompatDelegateImplV7.java:1703)
at android.support.v7.view.StandaloneActionMode.onMenuItemSelected(StandaloneActionMode.java:136)
I'm getting this error only when i try to delete the image after capturing.When i reload the page again and delete the image it works fine.
You might have problem here:
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = adapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
In this line
SparseBooleanArray selected = adapter
.getSelectedIds();
selected is not an array. so its size will always be one. and you are subtracting 1 from it thus making its size 0. Therefore, it'll always give array index out of bound exception whenever you'll try to access it.
A simple fiz may be this :
SparseBooleanArray[] selected = adapter
.getSelectedIds();

how to show different hints in editext programmatically

I am using an expandible view where parent is a text view and children are edittext views. I want to show different hints for different edit texts. I tried to do it programmatically but no success at all. Here is my code.
ContactFragment.java
public class ContactFragment extends Fragment {
private View mView;
Context mContext;
EditText edittext;
ExpandableListAdapter listAdapter;
ExpandableListView elv;
List<String> listDataHeader;
HashMap<String, List<String>> listDataChild;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
mContext = getActivity();
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
mView = inflater.inflate(R.layout.fragment_contact_details, container, false);
ExpandableListView elv = (ExpandableListView) mView.findViewById(R.id.list);
prepareListData();
listAdapter = new ExpandableListAdapter(mContext, listDataHeader,listDataChild);
elv.setAdapter(listAdapter);
elv.setOnGroupClickListener(new ExpandableListView.OnGroupClickListener() {
#Override
public boolean onGroupClick(ExpandableListView parent, View v,
int groupPosition, long id) {
// Toast.makeText(getApplicationContext(),
// "Group Clicked " + listDataHeader.get(groupPosition),
// Toast.LENGTH_SHORT).show();
return false;
}
});
// Listview Group expanded listener
elv.setOnGroupExpandListener(new ExpandableListView.OnGroupExpandListener() {
#Override
public void onGroupExpand(int groupPosition) {
Toast.makeText(mContext,
listDataHeader.get(groupPosition) + " Expanded",
Toast.LENGTH_SHORT).show();
}
});
// Listview Group collasped listener
elv.setOnGroupCollapseListener(new ExpandableListView.OnGroupCollapseListener() {
#Override
public void onGroupCollapse(int groupPosition) {
Toast.makeText(mContext,
listDataHeader.get(groupPosition) + " Collapsed",
Toast.LENGTH_SHORT).show();
}
});
// Listview on child click listener
elv.setOnChildClickListener(new ExpandableListView.OnChildClickListener() {
#Override
public boolean onChildClick(ExpandableListView parent, View v,
int groupPosition, int childPosition, long id) {
// TODO Auto-generated method stub
Toast.makeText(
mContext,
listDataHeader.get(groupPosition)
+ " : "
+ listDataChild.get(
listDataHeader.get(groupPosition)).get(
childPosition), Toast.LENGTH_SHORT)
.show();
return false;
}
});
return mView;
}
/*
* Preparing the list data
*/
private void prepareListData() {
listDataHeader = new ArrayList<String>();
listDataChild = new HashMap<String, List<String>>();
// Adding child data
listDataHeader.add("Contact Details");
// Adding child data
List<String> basic = new ArrayList<String>();
basic.add(" ");
basic.add(" ");
basic.add(" ");
basic.add(" ");
basic.add(" ");
listDataChild.put(listDataHeader.get(0), basic); // Header, Child data
}
}
ExpandableListAdapter.java
public class ExpandableListAdapter extends BaseExpandableListAdapter implements TextWatcher{
private Context _context;
private List<String> _listDataHeader; // header titles
// child data in format of header title, child title
private HashMap<String, List<String>> _listDataChild;
private ArrayList<EditText> editTextList = new ArrayList<EditText>();
int i=1;
String name,purpose;
public ExpandableListAdapter(Context context, List<String> listDataHeader,
HashMap<String, List<String>> listChildData) {
this._context = context;
this._listDataHeader = listDataHeader;
this._listDataChild = listChildData;
}
#Override
public Object getChild(int groupPosition, int childPosititon) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.get(childPosititon);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
final String childText = (String) getChild(groupPosition, childPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.fragment_contact_details_child, null);
}
EditText editetext = (EditText) convertView .findViewById(R.id.item);
while(i<6)
{
switch (i)
{
case 1:editetext.setHint("Contact Person");
break;
case 2:editetext.setHint("Contact Person Photo");
break;
case 3:editetext.setHint("Designation/Job");
break;
case 4:editetext.setHint("CEO Name");
break;
case 5:editetext.setHint("Company Name");
break;
}
i++;
}
editetext.addTextChangedListener(this);
editTextList.add(editetext);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return this._listDataChild.get(this._listDataHeader.get(groupPosition))
.size();
}
#Override
public Object getGroup(int groupPosition) {
return this._listDataHeader.get(groupPosition);
}
#Override
public int getGroupCount() {
return this._listDataHeader.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
String headerTitle = (String) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) this._context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.fragment_contact_details_parent, null);
}
TextView lblListHeader = (TextView) convertView
.findViewById(R.id.textViewParent);
lblListHeader.setTypeface(null, Typeface.BOLD);
lblListHeader.setText(headerTitle);
return convertView;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
#Override
public void beforeTextChanged(CharSequence s, int start, int count,
int after) {
// TODO Auto-generated method stub
}
#Override
public void onTextChanged(CharSequence s, int start, int before, int count) {
// TODO Auto-generated method stub
name=editTextList.get(0).getText().toString();
purpose=editTextList.get(1).getText().toString();
}
#Override
public void afterTextChanged(Editable s) {
// TODO Auto-generated method stub
System.out.println("Name is"+name);
System.out.println("purpose is"+purpose);
}
}
In your ExpandableListAdapter class under getChildView it looks like you are telling the app to loop through all of the hints and it finishes on "Company Name"
maybe change
while(i<6)
{
switch (i)
{
case 1:editetext.setHint("Contact Person");
break;
case 2:editetext.setHint("Contact Person Photo");
break;
case 3:editetext.setHint("Designation/Job");
break;
case 4:editetext.setHint("CEO Name");
break;
case 5:editetext.setHint("Company Name");
break;
}
i++;
}
to
switch (childPosition)
{
case 1:editetext.setHint("Contact Person");
break;
case 2:editetext.setHint("Contact Person Photo");
break;
case 3:editetext.setHint("Designation/Job");
break;
case 4:editetext.setHint("CEO Name");
break;
case 5:editetext.setHint("Company Name");
break;
}
actual i have better solution why dont u simply use xml code to put hint in your edit text.It will be easy for u and it is not mendetory to code it programmatically.hope u get it

How do i call a context menu on longclick in a ListView Item?

HomeFragment
imports;
public class HomeFragment extends Fragment {
// Declare Variables
ListView list;
TextView text;
ListViewAdapter adapter;
EditText editsearch;
String[] title;
String[] date;
String[] status;
ArrayList<ListCourse> arraylist = new ArrayList<ListCourse>();
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_home, container, false);
date = new String[] { "11/01/2011", "10/05/2006", "12/07/2002", "05/04/2011", "01/08/2012",
"09/12/2017", "22/06/2024", "31/01/2000", "10/10/2156", "10/02/2006" };
title = new String[] { "Programação", "Matemática", "Logística",
"Mobile", "Sistemas Operativos", "iOS", "Android", "Windows",
"Hardware", "Formação" };
status = new String[] { " ongoing ", " ongoing ",
" ongoing ", " standby ", " ongoing ", " ongoing ",
" ongoing ", " ongoing ", " finished ", " ongoing " };
// Locate the ListView in listview_main.xml
list = (ListView) rootView.findViewById(R.id.listview);
for (int i = 0; i < title.length; i++)
{
ListCourse wp = new ListCourse(date[i], title[i],
status[i]);
// Binds all strings into an array
arraylist.add(wp);
}
// Pass results to ListViewAdapter Class
adapter = new ListViewAdapter(getActivity(), arraylist);
// Binds the Adapter to the ListView
list.setAdapter(adapter);
return rootView;
}
}
I just need 3 items on the context menu: Like, Comment and Favorite. I tried implementing various tutorials to no avail, my project consist of a MainActivity that has a slidermenu to open some fragments like this one where the list is and where I want to put the context menu.
Here´s my adapter:
public class ListViewAdapter extends BaseAdapter {
// Declare Variables
Context mContext;
LayoutInflater inflater;
private List<ListCourse> coursepopulatelist = null;
private ArrayList<ListCourse> arraylist;
public ListViewAdapter(Context context, List<ListCourse> coursepopulatelist) {
mContext = context;
this.coursepopulatelist = coursepopulatelist;
inflater = LayoutInflater.from(mContext);
this.arraylist = new ArrayList<ListCourse>();
this.arraylist.addAll(coursepopulatelist);
}
public class ViewHolder {
TextView title;
TextView date;
TextView status;
}
#Override
public int getCount() {
return coursepopulatelist.size();
}
#Override
public ListCourse getItem(int position) {
return coursepopulatelist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(final int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.title = (TextView) view.findViewById(R.id.title);
holder.date = (TextView) view.findViewById(R.id.date);
holder.status = (TextView) view.findViewById(R.id.status);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Set the results into TextViews
holder.title.setText(coursepopulatelist.get(position).getTitle());
holder.date.setText(coursepopulatelist.get(position).getDate());
holder.status.setText(coursepopulatelist.get(position).getStatus());
// Listen for ListView Item Click
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// Send single item click data to SingleItemView Class
Intent intent = new Intent(mContext, SingleItemView.class);
// Pass all data rank
intent.putExtra("title",(coursepopulatelist.get(position).getTitle()));
// Pass all data country
intent.putExtra("date",(coursepopulatelist.get(position).getDate()));
// Pass all data population
intent.putExtra("status",(coursepopulatelist.get(position).getStatus()));
// Pass all data flag
// Start SingleItemView Class
mContext.startActivity(intent);
}
});
return view;
}
// Filter Class
public void filter(String charText) {
charText = charText.toLowerCase(Locale.getDefault());
coursepopulatelist.clear();
if (charText.length() == 0) {
coursepopulatelist.addAll(arraylist);
}
else
{
for (ListCourse wp : arraylist)
{
if (wp.getDate().toLowerCase(Locale.getDefault()).contains(charText))
{
coursepopulatelist.add(wp);
}
}
}
notifyDataSetChanged();
}
}
Are the changes supposed to go in the adapter or the fragment? I tried several times with OnCreateContextMenu and ContextMenuSelectedItem cant get it to work on the fragment, also tried OnLongItemClick. Any help would be appreciated.
I managed to get one context menu working, right here:
#Override
public void onCreateContextMenu(ContextMenu menu, View v,
ContextMenuInfo menuInfo) {
super.onCreateContextMenu(menu, v, menuInfo);
AdapterContextMenuInfo info = (AdapterContextMenuInfo) menuInfo;
adapter = new ListViewAdapter(getActivity(), arraylist);
Object item = adapter.getItem(info.position);
menu.setHeaderTitle("Opções");
menu.add(0, v.getId(), 0, "Like");
menu.add(1, v.getId(), 0, "Comment");
menu.add(2, v.getId(), 0, "Favorite");
}
#Override
public boolean onContextItemSelected(MenuItem item) {
if (item.getTitle() == "Like") {
addLike(item.getItemId());
} else if (item.getTitle() == "Comment") {
} else if (item.getTitle() == "Favorite") {
// code
} else {
return false;
}
return true;
}
public void addLike(int id){
}
Right after the return rootView in the HomeFragment. Also had to add android:longClickable="true" on the listview.xml or it would never work (I put it into the listviewitem.xml too just in case).
first set your listvieW as follow myListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
myListView.setAdapter(adapter);
then register for MultiChoiceModeListener and override his methods in your liking :)
myListView.setMultiChoiceModeListener(new AbsListView.MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position, long id, boolean checked) {
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// here you will inflate your CAB
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
}
});
}
Here is the link

Categories