I want to dynamically add items to my ListView in Android. However, I want this to be done when the user presses an action bar button. From what I have found, to do this, one needs to extend ListActivity and ActionBarActivity which Android doesn't support. How do I do this otherwise. Here is my code for MainActivity (which right now only extends ActionBarActivity):
import java.util.ArrayList;
import android.os.Bundle;
import android.support.v7.app.ActionBarActivity;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
public class MainActivity extends ActionBarActivity {
/** Items entered by the user is stored in this ArrayList variable */
ArrayList<String> list = new ArrayList<String>();
/** Declaring an ArrayAdapter to set items to ListView */
ArrayAdapter<String> adapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
adapter=new ArrayAdapter<String>(this, android.R.layout.simple_list_item_1,list);
setListAdapter(adapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.main_activity_actions, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle presses on the action bar items
switch (item.getItemId()) {
case R.id.action_new:
addListElement();
return true;
case R.id.action_settings:
return true;
default:
return super.onOptionsItemSelected(item);
}
}
private void addListElement() {
// TODO Auto-generated method stub
}
}
In your activity_main.xml add a listview.. then use like below...
ListView lv = (ListView) findViewById(R.id.listViewId);
lv.setAdapter(adapter);
remove setListAdapter(adapter);
private void addListElement(String value) {
list.add(value);
adapter.notifyDataSetChanged();
}
OR
private void addListElement(String value) {
adapter.add(value);
}
Related
I am following a tutorial 11. Exercise: Using the contextual action mode
But I am having this error :
mActionMode = Display.this.startActionMode(mActionModeCallback);
view.setSelected(true);
Error: The method startActionMode(ActionMode.Callback) in the type Activity is not applicable for the arguments (ActionMode.Callback)
I checked this stackoverflow answer
they said to add
ActionBarActivity activity=(ActionBarActivity)getActivity();
activity.startSupportActionMode(modeCallBack);
I had this error
The method getActivity() is undefined for the type Display
what I am doing wrong ? the below is my code.
package com.example.sqlfirst;
import android.os.Build;
import android.os.Bundle;
import android.support.v4.app.Fragment;
import android.support.v4.app.FragmentTransaction;
import android.support.v7.app.ActionBar;
import android.support.v7.app.ActionBar.Tab;
import android.support.v7.app.ActionBarActivity;
import android.util.Log;
import android.view.Menu;
import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.support.v4.app.NavUtils;
import android.support.v7.app.ActionBarActivity;
import android.support.v7.view.ActionMode;
import android.view.ActionMode.Callback;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.widget.AdapterView;
import android.widget.Toast;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.GridView;
public class Display extends ActionBarActivity {
private final static String TAG = "MainActivity";
protected Object mActionMode;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.grid_main);
//have to use getSupportActionBar from android.support.v7.app
// ActionBar actionBar = getSupportActionBar();
//getActionBar().setDisplayHomeAsUpEnabled(true);
ActionBarActivity activity=(ActionBarActivity)getActivity();
activity.startSupportActionMode(modeCallBack);
View view = findViewById(R.id.gridview);
view.setOnLongClickListener(new View.OnLongClickListener() {
// called when the user long-clicks on someView
public boolean onLongClick(View view) {
if (mActionMode != null) {
return false;
}
// start the CAB using the ActionMode.Callback defined above
mActionMode = Display.this.startActionMode(mActionModeCallback);
view.setSelected(true);
return true;
}
});
GridView gridview = (GridView) findViewById(R.id.gridview);
gridview.setAdapter(new ImageAdapter(this));
gridview.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> parent, View v, int position, long id) {
// Send intent to SingleViewActivity
Intent i = new Intent(getApplicationContext(), SingleViewActivity.class);
// Pass image index
i.putExtra("id", position);
startActivity(i);
} });
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.activity_main_actions, menu);
return super.onCreateOptionsMenu(menu);
}
public boolean onOptionsItemSelected(MenuItem item)
{
super.onOptionsItemSelected(item);
switch (item.getItemId()){
case R.id.ic_action_person:
Toast.makeText(this, "Create a new account please", Toast.LENGTH_SHORT).show();
Intent intent = new Intent(this, Register.class);
startActivity(intent);
return true;
case R.id.ic_action_search:
Toast.makeText(this, "Search for new images", Toast.LENGTH_SHORT).show();
Intent isearch= new Intent(this,Search.class);
startActivity(isearch);
return true;
case R.id.ic_action_picture:
Toast.makeText(this, "Search for new photos", Toast.LENGTH_SHORT).show();
Intent iphotos= new Intent(this,Display.class);
startActivity(iphotos);
return true;
}
return true;
}
private ActionMode.Callback mActionModeCallback = new ActionMode.Callback() {
// Called when the action mode is created; startActionMode() was called
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// inflate a menu resource providing context menu items
MenuInflater inflater = mode.getMenuInflater();
// assumes that you have "contexual.xml" menu resources
inflater.inflate(R.menu.activity_main_actions, menu);
return true;
}
// called each time the action mode is shown. Always called after
// onCreateActionMode, but
// may be called multiple times if the mode is invalidated.
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false; // Return false if nothing is done
}
// called when the user selects a contextual menu item
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.ic_action_picture:
Toast.makeText(Display.this, "Selected menu",
Toast.LENGTH_LONG).show();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
}
// called when the user exits the action mode
public void onDestroyActionMode(ActionMode mode) {
mActionMode = null;
}
};
}
Your Display class is extending ActionBarActivity, that means that it´s an Activity so there´s no need to use getActivity(), you can directly make use of the methods like this:
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
/* this method is available within your ActionBarActivity*/
startSupportActionMode(modeCallBack);
setContentView(R.layout.grid_main);
// The rest of your code comes here
}
I'm trying to implement a Contextual Action Bar (CAB) but whenever I long click an item it is not showing the item as selected (highlighted) so I'm not able to select multiple items to batch delete either. Below is the fragment attempting to utilize a CAB.
package com.garciaericn.memoryvault.main;
import android.app.Fragment;
import android.os.Bundle;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AbsListView;
import android.widget.AdapterView;
import android.widget.ListView;
import android.widget.Toast;
import com.garciaericn.memoryvault.R;
import com.garciaericn.memoryvault.data.Memory;
import com.garciaericn.memoryvault.data.MemoryAdapter;
import com.parse.DeleteCallback;
import com.parse.FindCallback;
import com.parse.ParseException;
import java.util.List;
public class MemoriesFragment extends Fragment implements AbsListView.MultiChoiceModeListener, AdapterView.OnItemClickListener {
ListView memoriesListView;
MemoryAdapter memoryAdapter;
public MemoriesFragment() {
// Mandatory empty constructor
}
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setHasOptionsMenu(true);
memoryAdapter = new MemoryAdapter(getActivity());
}
#Override
public View onCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
View view = inflater.inflate(R.layout.fragment_memories, container);
memoriesListView = (ListView) view.findViewById(R.id.listView);
memoriesListView.setAdapter(memoryAdapter);
memoriesListView.setOnItemClickListener(this);
memoriesListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
memoriesListView.setMultiChoiceModeListener(this);
return view;
}
private void refreshMemories() {
Memory.getQuery().findInBackground(new FindCallback<Memory>() {
#Override
public void done(List<Memory> memoryList, ParseException e) {
memoryAdapter.loadObjects();
}
});
}
#Override
public void onStart() {
super.onStart();
refreshMemories();
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
switch (item.getItemId()) {
case R.id.action_sync: {
refreshMemories();
Toast.makeText(getActivity(), "Refreshed from fragment", Toast.LENGTH_SHORT).show();
return true;
}
}
return super.onOptionsItemSelected(item);
}
#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 onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = mode.getMenuInflater();
inflater.inflate(R.menu.context_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.action_delete:
Toast.makeText(getActivity(), "Delete!", Toast.LENGTH_SHORT).show();
// TODO: Delete item
mode.finish(); // Action picked, so close the CAB
return true;
}
return false;
}
#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 void onItemClick(AdapterView<?> parent, View view, int position, long id) {
Memory memory = memoryAdapter.getItem(position);
/*// Un-comment to delete item
memory.deleteInBackground(new DeleteCallback() {
#Override
public void done(ParseException e) {
refreshMemories();
}
});
*/
Toast.makeText(getActivity(), memory.toString() + " was tapped", Toast.LENGTH_SHORT).show();
}
}
If you are implementing custom adapter you need to implement Checkable layout for listview item.
Check this Github page
which explains implementation of Checkable layout with demo adapter.
Use in in your custom list item layout like:
<your.package.CheckableLayout ... />
-Hey correct me if i am wrong I found in your code that you are implementing OnItemClickListener instead use AdapterView.OnItemLongClickListener as you wants you action on Long Click item.
Hello my application takes a picture/video or choose one from gallery and then try to send to a contact, the taking part works fine the problem is to send i have a ListActivity which indeed shows my contacts and i cand do single select o multiple select, when i select 1 or more a Send Image (Button) should appear in the action bar allowing continue to next stage, the problem is that the ListActivity does not have a ActionBar at all! so when i select friend the app crashes please help me implementing this idea...
My codes:
RecipientsActivity (ListView showing the friends)
package com.gorydev.selfdestructapp;
import android.app.AlertDialog;
import android.app.ListActivity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import com.parse.FindCallback;
import com.parse.ParseException;
import com.parse.ParseObject;
import com.parse.ParseQuery;
import com.parse.ParseRelation;
import com.parse.ParseUser;
import java.util.ArrayList;
import java.util.List;
public class RecipientsActivity extends ListActivity{
protected List<ParseUser> mFriends;
protected ParseRelation<ParseUser> mFriendsRelation;
protected ParseUser mCurrentUser;
protected MenuItem mSendMenuItem;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_recipients);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);// para permitir la seleccion multiple de amigos
}
#Override
public void onResume() {
super.onResume();
mCurrentUser = ParseUser.getCurrentUser();
mFriendsRelation = mCurrentUser.getRelation(ParseContants.KEY_FRIENDS_RELATION);
ParseQuery<ParseUser> query = mFriendsRelation.getQuery();
query.orderByAscending(ParseContants.KEY_USERNAME);
query.findInBackground(new FindCallback<ParseUser>() {
#Override
public void done(List<ParseUser> parseUsers, ParseException e) {
if(e == null) {
mFriends = parseUsers;
String[] usersnames = new String[mFriends.size()];
int i = 0;
for (ParseUser user : mFriends) { //Obtengo todos los nombres de usuario que estan en mUsers
usersnames[i] = user.getUsername();
i++;
}
//Ahora se crea el adaptador que mostrara los datos en el ListView
ArrayAdapter<String> adapter = new ArrayAdapter<String>(getListView().getContext(), //esto porque no es una Activity
android.R.layout.simple_list_item_checked,
usersnames);
setListAdapter(adapter);
}else{
//Fail
AlertDialog.Builder builder = new AlertDialog.Builder(getListView().getContext());
builder.setMessage(R.string.query_friends_error);
builder.setTitle(R.string.query_friends_title);
builder.setPositiveButton(android.R.string.ok, null);
AlertDialog dialog = builder.create();
dialog.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.menu_recipients, menu);
mSendMenuItem = menu.getItem(0);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
switch(id) {
case R.id.action_settings:
return true;
case R.id.action_send:
ParseObject message = createMessage();
//send(message);
return true;
}
return super.onOptionsItemSelected(item);
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
super.onListItemClick(l, v, position, id);
if(l.getCheckedItemCount() >= 1)
mSendMenuItem.setVisible(true);
else
mSendMenuItem.setVisible(false);
}
protected ParseObject createMessage(){
ParseObject message = new ParseObject(ParseContants.CLASS_MESSAGES);
message.put(ParseContants.KEY_SENDER_ID, ParseUser.getCurrentUser().getObjectId());
message.put(ParseContants.KEY_SENDER_NAME, ParseUser.getCurrentUser().getUsername());
message.put(ParseContants.KEY_RECIPIENT_IDS, getRecipientIds());
return message;
}
private ArrayList<String> getRecipientIds() {
ArrayList<String> recipientIds = new ArrayList<String>();
for(int i=0; i<getListView().getCount(); i++){
if(getListView().isItemChecked(i)){
recipientIds.add(mFriends.get(i).getObjectId());
}
}
return recipientIds;
}
//TODO BUG when choosing file the app crashes!!!!!!!!
}
The RecipientsMenu.xml file (in which i have my menu items):
<menu xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
tools:context="com.gorydev.selfdestructapp.RecipientsActivity">
<item android:id="#+id/action_send"
android:title="#string/action_send_title"
android:orderInCategory="100"
app:showAsAction="always"
android:visible="false"
android:icon="#drawable/ic_action_send_now"/>
</menu>
guys please provide examples, i have search but is confussing for me
This would be simpler if you could manage to implement a ActionBar library, such as Sherlock.
private class RecipientsActivity extends SherlockListActivity {
}
Add below code in your onCreate() method:
setHasOptionsMenu(true);
and call super method in onCreateOptionsMenu() method like below:
#Override
public void onCreateOptionsMenu(Menu menu, MenuInflater inflater) {
// TODO Add your menu entries here
super.onCreateOptionsMenu(menu, inflater);
}
And use Contextual Action Bar as suggested by Apurva.
I had the same problem and i solved it by writing my own class like below :
public class ActionBarListActivity extends ActionBarActivity {
private ListView mListView;
protected ListView getListView() {
if (mListView == null) {
mListView = (ListView) findViewById(android.R.id.list);
}
return mListView;
}
protected void setListAdapter(ListAdapter adapter) {
getListView().setAdapter(adapter);
}
protected ListAdapter getListAdapter() {
ListAdapter adapter = getListView().getAdapter();
if (adapter instanceof HeaderViewListAdapter) {
return ((HeaderViewListAdapter)adapter).getWrappedAdapter();
} else {
return adapter;
}
}
}
and then you can extend it instead of ListActivity like this :
public class RecipientsActivity extends ActionBarListActivity {
.
.
.
}
I have an application with a list view and a custom adapter where I add custom objects to the list view. I know how to delete objects through long-pressing one of the list items in the list, but I have a trash can action bar button and I want it so that when you click on that button, it brings up the same CAB as if you were long-pressing a list item, and I want the user to be able to select multiple list items, and then click a delete button on the CAB.
What I have tried:
package viva.inspection.com.inspectionpicker;
import android.app.Activity;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.text.TextUtils;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.widget.AbsListView;
import android.widget.Adapter;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.ListView;
import android.widget.Toast;
import java.lang.reflect.Array;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.GregorianCalendar;
import java.util.HashSet;
import java.util.List;
import viva.inspection.com.inspectionpicker.R;
public class ListActivity extends Activity {
private static ArrayList<InspectionItem> inspections;
private static final String s = "inspection list";
public static final String PREFS_NAME = "MyPrefsFile";
ListView inspectionList;
private final int GET_VALUE=111;
private final int GET_VAL = 11;
private MyAdapter listviewadapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list);
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
inspectionList = (ListView) findViewById(R.id.listView);
inspectionList.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
inspections = new ArrayList<InspectionItem>();
inspections.add(new InspectionItem(new GregorianCalendar(7,15,14), "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", new ArrayList<String>()));
if(getIntent().getStringExtra("NEW_VALUE") != null) {
//addItems(getIntent().getStringExtra("NEW_VALUE"));
SharedPreferences.Editor edit = settings.edit();
edit.putString("myKey", TextUtils.join(",", inspections));
edit.commit();
}
if(!(settings.getString("myKey", "hi").equals("hi"))) {
//We have saved values. Grab them.
} else {
//We have no saved values
inspections = new ArrayList<InspectionItem>();
inspections.add(new InspectionItem(new GregorianCalendar(7,15,14), "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", "hi", new ArrayList<String>()));
}
listviewadapter = new MyAdapter(this, R.layout.row_layout,
inspections);
inspectionList.setAdapter(listviewadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.list, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch(id) {
case R.id.action_settings:
return true;
case R.id.action_new:
Intent intent = new Intent(this, InitialChoose.class);
startActivity(intent);
return true;
case R.id.action_delete:
inspectionList.setOnItemSelectedListener(new ActionBarCallBack());
startActionMode(new ActionBarCallBack());
//mActionMode.finish();
return true;
}
return super.onOptionsItemSelected(item);
}
class ActionBarCallBack implements ListView.OnItemSelectedListener, ActionMode.Callback {
ActionMode activeMode;
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.delete:
// Calls getSelectedIds method from ListViewAdapter Class
SparseBooleanArray selected = listviewadapter
.getSelectedIds();
// Captures all selected ids with a loop
for (int i = (selected.size() - 1); i >= 0; i--) {
if (selected.valueAt(i)) {
InspectionItem selecteditem = listviewadapter
.getItem(selected.keyAt(i));
// Remove selected items following the ids
listviewadapter.remove(selecteditem);
}
}
// Close CAB
mode.finish();
return true;
default:
return false;
}
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
return true;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
// TODO Auto-generated method stub
listviewadapter.removeSelection();
}
#Override
public boolean onPrepareActionMode(final ActionMode mode, Menu menu) {
// TODO Auto-generated method stub
return false;
}
#Override
public void onItemSelected(AdapterView<?> adapterView, View view, int i, long l) {
listviewadapter.toggleSelection(i);
final int checkedCount = inspectionList.getCheckedItemCount();
// Set the CAB title according to total checked items
activeMode.setTitle(checkedCount + " Selected");
}
#Override
public void onNothingSelected(AdapterView<?> adapterView) {
}
}
/*
#Override
protected void onActivityResult(int requestCode, int resultCode, Intent data) {
super.onActivityResult(requestCode, resultCode, data);
if(resultCode==RESULT_OK){
if(requestCode == GET_VALUE){
if(data.getStringExtra("NEW_VALUE")!=null && data.getStringExtra("NEW_VALUE").length()>0){
addItems(data.getStringExtra("NEW_VALUE"));
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SharedPreferences.Editor edit = settings.edit();
edit.putString("myKey", TextUtils.join(",", inspections));
edit.commit();
}
}
}
} */
}
Basically, with this code, if I click on the trash-can action bar button, the CAB shows up, but I can't select any items on the list and proceed to delete them. Any help is greatly appreciated.
This is a tricky one. I used CheckedTextView's for multiple selections inside the list however when the list scrolls the adapter re-uses the old views and sometimes checks the wrong items. To overcome that I used an array of all the currently checked items, so the adapter can know which items should be checked.
Before going back to the original list you need to call notifyDataSetChanged(), which notifies to redrawn the visible views therefore uncheck/delete the selections (depends on what action you chose back at the CAB).
package com.example.simon.cabdelete;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.ActionMode;
import android.view.LayoutInflater;
import android.view.Menu;
import android.view.MenuItem;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.ArrayAdapter;
import android.widget.CheckedTextView;
import android.widget.ListView;
import java.util.ArrayList;
import java.util.List;
/**
* Created by Simon on 2014 Jul 18.
*/
public class MainActivity extends Activity {
private final static String TAG = "MainActivity";
MyAdapter mAdapter;
ListView mListView;
List<String> mListArray;
SparseBooleanArray mCheckedItems;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
mListView = (ListView) findViewById(R.id.listView);
// Default list item click listener
mListView.setOnItemClickListener(new AdapterView.OnItemClickListener(){
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
// Do something on normal click
}
});
mCheckedItems = new SparseBooleanArray();
int size = 20;
mListArray = new ArrayList<String>(size);
for (int i=0; i<size; i++)
mListArray.add("Item "+i);
mAdapter = new MyAdapter(this, R.layout.list_item, mListArray);
mListView.setAdapter(mAdapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
getMenuInflater().inflate(R.menu.main, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
switch (id) {
case R.id.action_settings:
break;
case R.id.action_delete:
startActionMode(new ActionBarCallBack());
break;
}
return super.onOptionsItemSelected(item);
}
public class MyAdapter extends ArrayAdapter<String> {
List<String> items;
int itemResource;
LayoutInflater inflater;
public MyAdapter(Context ctx, int resource, List<String> objects) {
super(ctx, resource, objects);
this.items = objects;
this.itemResource = resource;
this.inflater = ((MainActivity)ctx).getLayoutInflater();
}
#Override
public View getView(int pos, View convertView, ViewGroup parent) {
// (Re)Use convertView
if (convertView == null) {
convertView = inflater.inflate(itemResource, parent, false);
}
CheckedTextView checkView = (CheckedTextView) convertView;
checkView.setText(items.get(pos));
if (mCheckedItems.get(pos))
checkView.setChecked(true);
else
checkView.setChecked(false);
return convertView;
}
}
public class ActionBarCallBack implements ListView.OnItemClickListener,
ActionMode.Callback {
ActionMode actionMode;
AdapterView.OnItemClickListener previousListener;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
Log.v(TAG, "Action mode started");
actionMode = mode;
mode.getMenuInflater().inflate(R.menu.cab_menu, menu);
previousListener = mListView.getOnItemClickListener();
mListView.setOnItemClickListener(this);
mCheckedItems = new SparseBooleanArray(mListView.getCount());
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.delete:
Log.v(TAG, "Deleting "+mCheckedItems.size()+" items");
for (int i= mCheckedItems.size()-1; i>=0; i--) {
int key = mCheckedItems.keyAt(i);
Log.v(TAG, "Removing array item # " + key);
mListArray.remove(key);
}
mode.finish();
return true;
default:
return false;
}
}
#Override
public void onDestroyActionMode(ActionMode mode) {
Log.v(TAG, "Exiting action mode.");
mListView.setOnItemClickListener(previousListener);
mCheckedItems.clear();
mAdapter.notifyDataSetChanged();
}
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
CheckedTextView checkView = (CheckedTextView) view;
boolean state = checkView.isChecked();
checkView.setChecked(!state);
if (!mCheckedItems.get(position))
mCheckedItems.put(position, true);
else
mCheckedItems.delete(position);
actionMode.setTitle(mCheckedItems.size() + " Items selected");
Log.v(TAG, "Action item # " + position +
" clicked. It's state now is " + state);
}
}
}
And here are my xml files create the whole look:
res/layout/activity_main.xml:
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:paddingLeft="#dimen/activity_horizontal_margin"
android:paddingRight="#dimen/activity_horizontal_margin"
android:paddingTop="#dimen/activity_vertical_margin"
android:paddingBottom="#dimen/activity_vertical_margin"
tools:context=".MainActivity">
<ListView
android:id="#+id/listView"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:drawSelectorOnTop="true"/>
<!-- Note that drawSelectorOnTop is important as it lets
the CheckedTextViews to be clicked in a normal way too-->
</RelativeLayout>
res/layout/list_item.xml:
<CheckedTextView
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:padding="10dp"
android:background="#drawable/list_selector"/>
res/drawable/list_selector.xml:
<selector xmlns:android="http://schemas.android.com/apk/res/android">
<item android:drawable="#color/item_default" android:state_checked="false"/>
<item android:drawable="#color/item_checked" android:state_checked="true"/>
</selector>
res/values/colors.xml:
<resources>
<color name="item_default">#33B5E5</color>
<color name="item_checked">#0095CC</color>
</resources>
I am attempting to get my app to open a settings menu screen and return. The problem I am having is when in the settings page, upon pressing the back button, the app closes. I am VERY new to programming in general after fighting this for about 8 hours I am ready to ask for help!
Here is the code I have written
`package com.bowersoftware.connecttozcu;
import android.app.Activity;
import android.os.Bundle;
import android.view.Menu;
import android.view.MenuInflater;
import android.view.MenuItem;
import android.widget.ArrayAdapter;
import android.widget.Spinner;
import android.widget.Toast;
public class ConnecttoZCU extends Activity {
private Spinner mEngineSpinner;
private Spinner mUnitsSpinner;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
mEngineSpinner = (Spinner) findViewById(R.id.engineSpinner);
ArrayAdapter<CharSequence> adapter = ArrayAdapter.createFromResource(
this, R.array.engine, android.R.layout.simple_spinner_item);
adapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mEngineSpinner.setAdapter(adapter);
}
private void ConnectSettings() {
setContentView(R.layout.settings);
mUnitsSpinner = (Spinner) findViewById(R.id.unitsSpinner);
ArrayAdapter<CharSequence> settingsadapter = ArrayAdapter.createFromResource(
this, R.array.units, android.R.layout.simple_spinner_item);
settingsadapter.setDropDownViewResource(android.R.layout.simple_spinner_dropdown_item);
mUnitsSpinner.setAdapter(settingsadapter);
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.option_menu, menu);
return true;
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle item selection
switch (item.getItemId()) {
case R.id.scan:
Toast.makeText(this, "Scan", Toast.LENGTH_LONG).show();
return true;
case R.id.settings:
Toast.makeText(this, "Settings", Toast.LENGTH_LONG).show();
ConnectSettings();
return true;
default:
return super.onOptionsItemSelected(item);
}
}
}`
I am sure it is something silly I am missing but just can't figure it out.
Thanks, Jason
ContactsSetting should be separate Activity.
At the moment you have single Activity, so when you press Back button the application is closed.
To start new activity use:
startActivity(new Intent(this, ContactsSetting.class));