I want to delete the items from the fragments. When long click on the items than a action bar is changed and a delete button appears. I click on the delete button The item seems to be deleted from the list view. But when I restart the app the item appears again.
public class ReadFragment extends Fragment {
ListView spinner;
TextView empty;
String selected;
List<String> list;
String[] filenames;
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container,
Bundle savedInstanceState) {
View rootView = inflater.inflate(R.layout.fragment_read, container,
false);
spinner = (ListView) rootView.findViewById(R.id.spinner2);
this.spinner.setEmptyView(rootView.findViewById(R.id.emptyElement));
getFilenames();
getactionbar();
return rootView;
}
private void getFilenames() {
// TODO Auto-generated method stub
filenames = getActivity().fileList();
list = new ArrayList<String>();
for (int i = 0; i < filenames.length; i++) {
// Log.d("Filename", filenames[i]);
list.add(filenames[i]);
}
ArrayAdapter<String> filenameAdapter = new ArrayAdapter<String>(
getActivity(), android.R.layout.simple_list_item_1,
android.R.id.text1, list);
spinner.setAdapter(filenameAdapter);
spinner.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
selected = ((TextView) view).getText().toString();
Intent intent = new Intent(getActivity(), ReadData.class);
intent.putExtra("key", selected);
startActivity(intent);
}
});
}
private void getactionbar() {
// TODO Auto-generated method stub
spinner.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
spinner.setMultiChoiceModeListener(new MultiChoiceModeListener() {
#Override
public void onItemCheckedStateChanged(ActionMode mode, int position,
long id, boolean checked) {
// Here you can do something when items are selected/de-selected,
// such as update the title in the CAB
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.ic_action_discard:
deletefiles();
Toast.makeText(getActivity(), "Deleted", Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
private void deletefiles() {
// TODO Auto-generated method stub
SparseBooleanArray checkedItemPositions = spinner.getCheckedItemPositions();
int itemCount = spinner.getCount();
for(int i=itemCount-1; i >= 0; i--){
if(checkedItemPositions.get(i)){
filenameAdapter.remove(list.get(i));
}
}
checkedItemPositions.clear();
filenameAdapter.notifyDataSetChanged();
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// Here you can make any necessary updates to the activity when
// the CAB is removed. By default, selected items are deselected/unchecked.
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
// Here you can perform updates to the CAB due to
// an invalidate() request
return false;
}
});
}
}
Can anyone help me deleting the item forever, I mean once it is deleted it should not appear in the listview again when the app is relaunched.
Try, tries it worked here
final Button btnRemove = (Button) findViewById(R.id.button1);
btnRemove.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
lst.remove(adapter.getItem(2));
adapter.notifyDataSetChanged();
}
});;
I don't know if it is intentionally, but you copy the items from the Activity into another array before passing it to the Adapter. So when you call adapter.remove() it only removes the item from the new one leaving the original List in the Activity untuched (guess you save that one to storage in the Activitys onPause or something).
Related
I need to remove selected by chechbox items from ListView using a button from Options Menu. After selecting items, I'm trying to click delete button on Options Menu and then my application crashes. When I'm using same code when button is at the same xml where the listview everything goes correctly, problem only happen when I'm trying to do same thing using Options Menu Item.
EDIT: I'm pasting my whole code
This is my code from main_activity.java
public class MainActivity extends AppCompatActivity {
private ArrayList<String> items;
private ArrayAdapter<String> itemsAdapter;
private ListView lvItems;
private static final String TAG = "MainActivity";
Button delete;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(layout.activity_main);
lvItems = (ListView) findViewById(id.lvItems);
lvItems.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
items = new ArrayList<String>();
itemsAdapter = new ArrayAdapter<String>(this, layout.item_to_do, id.task_title, items);
lvItems.setAdapter(itemsAdapter);
items.add("Pierwsza rzecz");
items.add("Druga rzecz");
delete = (Button) findViewById(id.action_delete_task);
setupListViewListener();
}
public void onCheckboxClicked(View view) {
// Is the view now checked?
boolean checked = ((CheckBox) view).isChecked();
// Check which checkbox was clicked
switch (view.getId()) {
case id.task_delete:
if (checked)
break;
}
}
private void setupListViewListener() {
lvItems.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapter, View view, int position, long id) {
items.remove(position);
itemsAdapter.notifyDataSetChanged();
return true;
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(final MenuItem item) {
switch (item.getItemId()) {
case id.action_add_task:
final EditText taskEditText = new EditText(this);
taskEditText.setAllCaps(true);
AlertDialog.Builder builder = new AlertDialog.Builder(this);
builder.setTitle("Add a new task");
builder.setMessage("What do you want to do next?");
builder.setView(taskEditText);
builder.setPositiveButton("Add", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
String task = String.valueOf(taskEditText.getText());
Log.d(TAG, "Task to add: " + task);
itemsAdapter.add(task);
Snackbar.make(findViewById(id.lvItems), string.add,
Snackbar.LENGTH_SHORT)
.show();
}
});
builder.setNegativeButton("Cancel", null);
AlertDialog dialog = builder.create();
dialog.show();
return true;
case id.action_delete_task:
delete.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
SparseBooleanArray checkedItemPositions = lvItems.getCheckedItemPositions();
int itemCount = lvItems.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
if (checkedItemPositions.get(i)) {
itemsAdapter.remove(items.get(i));
}
}
checkedItemPositions.clear();
itemsAdapter.notifyDataSetChanged();
}
});
default:
return super.onOptionsItemSelected(item);
}
}
}
delete is menu item not a view in your layout so you will not set click listener on it.
Remove Button delete from your class
And Just do like below
case id.action_delete_task:
SparseBooleanArray checkedItemPositions = lvItems.getCheckedItemPositions();
int itemCount = lvItems.getCount();
for (int i = itemCount - 1; i >= 0; i--) {
if (checkedItemPositions.get(i)) {
itemsAdapter.remove(items.get(i));
}
}
checkedItemPositions.clear();
itemsAdapter.notifyDataSetChanged();
Also I can not see onCreateOption menu in your code. This is used to inflate menu in your activity.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.your_menu, menu);
return true;
}
I have a listview in fragment and my problem is when I select items on listview then it's fine, but when I scroll my listview then item's background is checked for another items, but I don't want that. You can see my image, first I select 3 items (Browser, Calendar, Contact), when I scroll listview then 2 items (Dev tool, Camera) have a changed background, if I continue scroll then listview has more items like that.
Here is my code:
#SuppressLint("NewApi") public class Tab2 extends Fragment{
private PackageManager packageManager = null;
private List<ApplicationInfo> applist = null;
public static ApplicationAdapter listadaptor = null;
public static ListView list;
private ActionMode acMode;
private int counterChecked = 0;
private SparseBooleanArray sp;
public View onCreateView(LayoutInflater inflater, #Nullable ViewGroup container, #Nullable Bundle savedInstanceState) {
View v = inflater.inflate(R.layout.tab2test,container,false);
list = (ListView)v.findViewById(R.id.list_view2);
list.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
list.setItemsCanFocus(false);
packageManager = getActivity().getPackageManager();
applist = checkForLaunchIntent(packageManager.getInstalledApplications(PackageManager.GET_META_DATA));
listadaptor = new ApplicationAdapter(getActivity().getApplicationContext(),R.layout.snippet_list_row, applist);
list.setAdapter(listadaptor);
sp = list.getCheckedItemPositions();
list.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
//Here i set item's color and unselected color
view.setBackgroundColor(sp.get(position)? 0x9934B5E4: Color.WHITE);
if(counterChecked<1){
acMode = ((AppCompatActivity) getActivity()).startSupportActionMode(mActionModeCallback);
}
String str="";
int i=0;
for(i=0;i<sp.size();i++)
{
if(sp.valueAt(i)){
str+=sp.keyAt(i)+",";
}
}
if(list.isItemChecked(position)){
Log.d("list1", String.valueOf(position));
list.setItemChecked(position, true);
counterChecked++;
}else{
list.setItemChecked(position, false);
counterChecked--;
}
if(counterChecked<1){
mActionModeCallback.onDestroyActionMode(acMode);
}
}
});
return v;
}
private List<ApplicationInfo> checkForLaunchIntent(List<ApplicationInfo> list) {
ArrayList<ApplicationInfo> applist = new ArrayList<ApplicationInfo>();
for (ApplicationInfo info : list) {
try {
if(isSystemPackage(info)){
if (null != packageManager.getLaunchIntentForPackage(info.packageName)) {
applist.add(info);
}
}
} catch (Exception e) {
e.printStackTrace();
}
}
return applist;
}
private boolean isSystemPackage(ApplicationInfo AInfo) {
return ((AInfo.flags & ApplicationInfo.FLAG_SYSTEM) != 0) ? true
: false;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback(){
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.cab_menu, menu);
MainActivity.toolbar.setVisibility(View.GONE);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
mode.finish();
MainActivity.toolbar.setVisibility(View.VISIBLE);
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode arg0, Menu arg1) {
// TODO Auto-generated method stub
return false;
}
};
}
You actually trigger OnItemClickListener when scrolling which causes a multiple select for items that you didn't want to include.
A better approach would be using a checkBox inside your listView Item and mark the item as selected when the check box is checked: check out this link on how to Get Selected Item Using Checkbox in Listview.
If you incest on using onClick then you can implement longClickListener on your listView Items which may prevent get item selected when scrolling but my advice to you is to go with checkBoxes.
OnLongClickListener Implementation:
listView.setOnItemLongClickListener(new AdapterView.OnItemLongClickListener() {
public boolean onItemLongClick(AdapterView<?> arg0, View v,
int index, long arg3) {
// TODO Auto-generated method stub
String str=listView.getItemAtPosition(index).toString();
return true;
}
});
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... ;-)
Initially it shows the correct item selected...but after re-populating the list it shows the wrong item being selected...please help me find the mistake
Intially the list is populated in onCreate()
and is re-populated in onOptionsItemSelected(MenuItem item)
public class MainActivity extends Activity {
MyListActivity adapter;
ListView list;
String[] web = {
"jerry",
"walters"
} ;
Integer[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MyListActivity(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[+ position], Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
String[] web2 = {
"walters",
"jerry"
} ;
adapter = new MyListActivity(MainActivity.this, web2, imageId);
list.setAdapter(adapter);
return true;
}
return false;
}
}
You have this
web[position]
// get string from web string array not from web2 based on position
Position is the index.
web[0] = "jerry"
web[1] ="walters"
You are re-populating your listview with a different array.
web and web2 are two different arrays.
If you want to update , update the web array and call notifyDataSetChanged on your adapter to refresh listview
your are not updating your web array:
public class MainActivity extends Activity {
MyListActivity adapter;
ListView list;
String[] web = {
"jerry",
"walters"
} ;
Integer[] imageId = {
R.drawable.ic_launcher,
R.drawable.ic_launcher
};
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter = new MyListActivity(MainActivity.this, web, imageId);
list=(ListView)findViewById(R.id.listView1);
list.setAdapter(adapter);
list.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,int position, long id) {
Toast.makeText(MainActivity.this, "You Clicked at " +web[position], Toast.LENGTH_SHORT).show();
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_settings:
web = {//<--------------just update we array as well
"walters",
"jerry"
} ;
adapter = new MyListActivity(MainActivity.this, web, imageId);
list.setAdapter(adapter);
return true;
}
return false;
}
}
I guess it might because web and web2 have different order which leads to different answer?
String[] web = { "jerry", "walters"} ;
String[] web2 = {"walters", "jerry" } ;
I'm setting a Contextual Action Bar for my List in a Fragment.
Using ActionBarSherlock to get CAB with Multiple selection in pre-HONEYCOMB version of android.
I'm flowing this tutorial, but application crashes after performing a long click.
This is my code:
public class CreateFragment extends SherlockFragment {
private ArrayList<Game> myGames;
public ArrayAdapter<String> adapter;
private TipspromenadApplication app;
private ListView listView;
private ActionMode mActionMode;
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState){
View view = inflater.inflate(R.layout.fragment_create, container, false);
listView = (ListView) view.findViewById(R.id.createdGames);
View header = getActivity().getLayoutInflater().inflate(R.layout.list_header_create_fragment, null);
listView.addHeaderView(header);
final ArrayList<String> list = new ArrayList<String>();
for (int i = 0; i < myGames.size(); i++) {
list.add(myGames.get(i).getLocation() + " " + new SimpleDateFormat("dd/MM/yy", Locale.getDefault()).format(myGames.get(i).getEventDate()));
}
// adapter = new ArrayAdapter<String>(getActivity(), android.R.layout.simple_list_item_multiple_choice, list);
// listView.setAdapter(adapter);
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapter, View view, int position, long id) {
Intent intent= new Intent(getActivity(), CreateTabActivity.class);
intent.putExtra("GameID", position-1);
startActivity(intent);
}
});
listView.setOnItemLongClickListener(new OnItemLongClickListener() {
#Override
public boolean onItemLongClick(AdapterView<?> adapterView, View view, int position, long id) {
onListItemCheck(position);
return true;
}
});
listView.setAdapter(new SelectableAdapter(this, list));
return view;
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
app = (TipspromenadApplication) getActivity().getApplication();
this.myGames = app.loadGames();
}
//#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
if(mActionMode == null) {
// no items selected, so perform item click actions
} else
// add or remove selection for current list item
onListItemCheck(position);
}
private void onListItemCheck(int position) {
SelectableAdapter adapter = (SelectableAdapter) listView.getAdapter();
adapter.toggleSelection(position);
boolean hasCheckedItems = adapter.getSelectedCount() > 0;
if (hasCheckedItems && mActionMode == null)
// there are some selected items, start the actionMode
mActionMode = getSherlockActivity().startActionMode(new ActionModeCallback());
else if (!hasCheckedItems && mActionMode != null)
// there no selected items, finish the actionMode
mActionMode.finish();
if(mActionMode != null)
mActionMode.setTitle(String.valueOf(adapter.getSelectedCount()) + " selected");
}
private class SelectableAdapter extends ArrayAdapter<String>{
private SparseBooleanArray mSelectedItemsIds;
public SelectableAdapter(CreateFragment createFragment, ArrayList<String> list) {
super(getActivity(), android.R.layout.simple_list_item_1, list);
mSelectedItemsIds = new SparseBooleanArray();
}
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();// mSelectedCount;
}
public SparseBooleanArray getSelectedIds() {
return mSelectedItemsIds;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
if(convertView == null){
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(android.R.layout.simple_list_item_1, null);
}
((TextView) convertView).setText(getItem(position));
//change background color if list item is selected
convertView.setBackgroundColor(mSelectedItemsIds.get(position)? 0x9934B5E4: Color.TRANSPARENT);
return convertView;
}
}
private class ActionModeCallback implements ActionMode.Callback {
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// inflate contextual menu
mode.getMenuInflater().inflate(R.menu.create, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.share:
// do s.th.
mode.finish(); // Action picked, so close the CAB
return true;
case R.id.delete:
// do s.th.
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// remove selection
SelectableAdapter adapter = (SelectableAdapter) listView.getAdapter();
adapter.removeSelection();
mActionMode = null;
}
}
}
And this is the error in LogCat:
FATAL EXCEPTION: main
java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.damson.android.tipspromenad.tabs.CreateFragment$SelectableAdapter
at com.damson.android.tipspromenad.tabs.CreateFragment.onListItemCheck(CreateFragment.java:113)
at com.damson.android.tipspromenad.tabs.CreateFragment.access$2(CreateFragment.java:112)
at com.damson.android.tipspromenad.tabs.CreateFragment$2.onItemLongClick(CreateFragment.java:66)
at android.widget.AbsListView.performLongPress(AbsListView.java:2925)
at android.widget.AbsListView$CheckForLongPress.run(AbsListView.java:2875)
at android.os.Handler.handleCallback(Handler.java:615)
at android.os.Handler.dispatchMessage(Handler.java:92)
at android.os.Looper.loop(Looper.java:213)
at android.app.ActivityThread.main(ActivityThread.java:4787)
at java.lang.reflect.Method.invokeNative(Native Method)
at java.lang.reflect.Method.invoke(Method.java:511)
at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:789)
at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:556)
at dalvik.system.NativeStart.main(Native Method)
Sorry for a long question! I hope you can help me :) Thanks!
That tutorial does not use addHeaderView(). Your code uses addHeaderView(). Your error is involving the header view:
java.lang.ClassCastException: android.widget.HeaderViewListAdapter cannot be cast to com.damson.android.tipspromenad.tabs.CreateFragment$SelectableAdapter
This is because when you call addHeaderView(), getListAdapter() will no longer return your own adapter, but rather a new adapter, one that wraps yours and supplies the header view.
Call getWrappedAdapter() on the HeaderViewListAdapter to get your SelectableAdapter.
UPDATE
HeaderViewListAdapter wasThisReallySoHard=(HeaderViewListAdapter)listView.getAdapter();
SelectableAdapter adapter=(SelectableAdapter)wasThisReallySoHard.getWrappedAdapter();