How to implement checkbx with custom listview - android

   I want to make product list with their price,name,image and checkbox,
User checks the product as the user wants and then pass it to second activity,
       
 In second activity it display the item checked with their price,So what method i have to use specially for checkbox input,I am newbie to android so please help me,

I suppose you have a class Product with price, name ...
You have to create a layout (list_row.xml) with the format that you want, for example:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical" android:layout_width="match_parent"
android:background="?android:attr/activatedBackgroundIndicator"
android:layout_height="match_parent">
<TextView
android:id="#+id/tv_subtitle_list"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignLeft="#+id/tv_title_list"
android:layout_below="#+id/tv_title_list"
android:longClickable="true" />
<TextView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/tv_title_list"
android:longClickable="true" />
<ImageView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:layout_alignRight="#+id/tv_title_list"
android:layout_alignBottom="#+id/tv_title_list"
android:id="#+id/img_sync"
android:longClickable="true" />
</RelativeLayout>
After that, you need a List Adapter, the best way is create a Custom List adapter
public class ProductListAdapter extends ArrayAdapter<Product>
{
private List<Product> objects;
private Context context;
public ProductListAdapter(Context context, int textViewResourceId, List<Product> objects)
{
super(context, textViewResourceId, objects);
this.context = context;
this.objects = objects;
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Incidence getItem(int position) {
return objects.get(position);
}
#Override
public long getItemId(int position) {
if(objects.get(position)==null) return -1;
return objects.get(position).getId(); // your database id
}
#Override
public void addAll(Collection<? extends Product> objects) {
this.objects= new ArrayList<>(objects);
notifyDataSetChanged();
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
Incidence rowItem = getItem(position); // get selected item
if (convertView == null)
{
LayoutInflater mInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
convertView = mInflater.inflate(R.layout.list_row, null);
}
/* Access to row components */
TextView title = (TextView) convertView.findViewById(R.id.tv_title_list); // name
TextView subtitle = (TextView) convertView.findViewById(R.id.tv_subtitle_list); // price
ImageView img = (ImageView) convertView.findViewById(R.id.img_sync); // image
title.setText(rowItem.getName());
subtitle.setText(rowItem.getPrice());
img.setImageResource(android.R.drawable.ic_menu_share);
return convertView;
}
}
In your fragment or activity you create the adapter:
public class FragListIncidences extends ListFragment
{
public void initUI() // include this in your onCreate
{
mAdapter = new ProductListAdapter(getActivity(),
android.R.layout.simple_list_item_1, new ArrayList<Product>());
setListAdapter(mAdapter); // because of ListFragment
}
}
The checkbox functionality that you want can be implemented in two ways:
Add Cechbox component in your list_row.xml
You can use a contextual action mode menu. Here you have an example http://developer.android.com/intl/es/guide/topics/ui/menus.html#CAB
public void initUI() // include this in your onCreate
{
mAdapter = new ProductListAdapter(getActivity(),
android.R.layout.simple_list_item_1, new ArrayList<Product>());
setListAdapter(mAdapter); // because of ListFragment
mListView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
mListView.setMultiChoiceModeListener(new AbsListView.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
final int checkedCount = mListView.getCheckedItemCount();
mode.setTitle(checkedCount + " Selected");
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
// Respond to clicks on the actions in the CAB
switch (item.getItemId()) {
case R.id.action_get:
getSelectedItems();
mode.finish(); // Action picked, so close the CAB
return true;
default:
return false;
}
return false;
}
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
// Inflate the menu for the CAB
MenuInflater inflater = mode.getMenuInflater();
contextual_menu =menu;
inflater.inflate(R.menu.subactions, menu);
}
#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;
}
});
}
private void getSelectedItems() {
final SparseBooleanArray selected = mListView.getCheckedItemPositions();
for (int i = (selected.size() - 1); i >= 0; i--)
if (selected.valueAt(i))
doWhateverYouWant (selected.keyAt(i));
}

In java you have to instantiate each checkBox that you put into your layouts (i.e. CheckBox checkbox1 = new (Checkbox) findViewById(R.id.checkbox1);
Then all you have to do is put a few if() statements into your onCreate like this:
if(checkbox1.isChecked == true){
//send the info to your next activity
}else{
//nothing
}

Related

How to test a android project which includes edittext ,button and listview?

I did develop an android project which includes edittext , button and listview . I have a mainActivity which includes these views in it's layout.When user enter a text on Edittext and clikc the buttom ,text will transfer to listview.Up to here, everything is okey , I can do that.Addition to this,I did create class which is extended by ArrayAdapter because I want to optimize application.I want to test application with 1000 text etc ,thanks to this I can optimize my adapter, but I don not know how to I test it ?
public class TodoItemAdapter extends ArrayAdapter<TodoItem> {
int resource;
public TodoItemAdapter(Context context, int resource,List<TodoItem> objects) {
super(context, resource ,objects);
this.resource = resource ;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
TodoItem toDoItem = getItem(position);
String toDoTask = toDoItem.task;
String toDoDate = DateFormat.getDateInstance().format(toDoItem.enteringData );
String inflaterService = Context.LAYOUT_INFLATER_SERVICE;
LayoutInflater inflater = (LayoutInflater) getContext().getSystemService(inflaterService);
View toDoView = inflater.inflate(this.resource,null);
TextView taskView = (TextView) toDoView.findViewById(R.id.tvTask);
TextView dateView = (TextView) toDoView.findViewById(R.id.tvDate);
taskView.setText(toDoTask);
dateView.setText(toDoDate);
return toDoView;
}
}
public class MyActivity extends Activity {
private ArrayList <TodoItem> todoItems;
private TodoItemAdapter todoArrayAdapter ;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_my);
final EditText etTodo = (EditText) findViewById(R.id.etTodo);
Button btnAddTodo = (Button) findViewById(R.id.btnAddTodo);
ListView lvTodoItems = (ListView) findViewById(R.id.todoListView);
todoItems = new ArrayList<TodoItem>();// line1
todoArrayAdapter = new TodoItemAdapter(this,R.layout.todoitem,todoItems) ;//line2
lvTodoItems.setAdapter(todoArrayAdapter); //line3
//line1,line2 and line3 apply ( DataSource -> Adapter -> AdapterView ) schema.
btnAddTodo.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
todoItems.add(new TodoItem(etTodo.getText().toString()));
todoArrayAdapter.notifyDataSetChanged();
etTodo.setText("");
}
});
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.my, 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();
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
}
You can use Espresso to write Android UI tests like the following:
public void testAdapter() {
for (int i = 0; i < 1000; i++) {
onView(withId(R.id.etTodo))
.perform(typeText("Todo #" + i));
onView(withId(R.id.btnAddTodo))
.perform(click());
}
}

How do I add activities to a favourites list?

I would like to have a favourites list in my app but I'm not sure how to do it. Basically when a star button is pressed in the menu bar of an activity I would like a custom link/button to bet added to a favourites menu in another activity.
Any help at all is great.
thanks in advance!
Edit here is where I'm at:
public class MainActivity extends Activity implements OnItemClickListener {
ListView lv;
List<ListViewItem> items;
CustomListViewAdapter adapter;
#Override
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
ListViewItem item = items.get(position);
items.remove(item);
adapter = new CustomListViewAdapter(this, items);
lv.setAdapter(adapter);
}
public static final String PREFS = "examplePrefs";
String LINK = "MainActivity";
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
lv = (ListView) findViewById(R.id.ListView);
items = new ArrayList<MainActivity.ListViewItem>();
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_launcher;
Title = "Item1";
SubTitle = "Item1 desciption";
}});
items.add(new ListViewItem()
{{
ThumbnailResource = R.drawable.ic_launcher;
Title = "Item2";
SubTitle = "Item2 desciption";
}});
adapter = new CustomListViewAdapter(this,items);
lv.setAdapter(adapter);
lv.setOnItemClickListener(this);
class ListViewItem
{
public int ThumbnailResource;
public String Title;
public String SubTitle;
}
Here is my listview adapter .java
public class CustomListViewAdapter extends BaseAdapter
LayoutInflater inflater;
List<ListViewItem> items;
public CustomListViewAdapter(Activity context, List<ListViewItem> items) {
super();
this.items = items;
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListViewItem item = items.get(position);
View vi=convertView;
if(convertView==null)
vi = inflater.inflate(R.layout.item_row, null);
ImageView imgThumbnail = (ImageView) vi.findViewById(R.id.imgThumbnail);
TextView txtTitle = (TextView) vi.findViewById(R.id.txtTitle);
TextView txtSubTitle = (TextView) vi.findViewById(R.id.txtSubTitle);
imgThumbnail.setImageResource(item.ThumbnailResource);
txtTitle.setText(item.Title);
txtSubTitle.setText(item.SubTitle);
return vi;
}
Here is my item row .xml
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
android:id="#+id/relativeLayout1"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
xmlns:android="http://schemas.android.com/apk/res/android"
android:padding="5dip">
<ImageView
android:layout_width="78dip"
android:layout_height="78dip"
android:id="#+id/imgThumbnail"
android:layout_alignParentLeft="true"
android:layout_centerInParent="true"
android:layout_marginLeft="-3dip"
android:scaleType="centerInside">
</ImageView>
<TextView
android:textAppearance="?android:attr/textAppearanceLarge"
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtTitle"
android:layout_toRightOf="#+id/imgThumbnail"
android:layout_marginTop="6dip"
android:layout_marginLeft="6dip">
</TextView>
<TextView
android:layout_height="wrap_content"
android:text="TextView"
android:layout_width="wrap_content"
android:id="#+id/txtSubTitle"
android:layout_toRightOf="#+id/imgThumbnail"
android:layout_below="#+id/txtTitle"
android:layout_marginTop="3dip"
android:layout_marginLeft="6dip">
</TextView>
I'm stuck on trying to get all necessary information to populate a listview item from the Action Bar item that I've added in my activity that is to be faourited.
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.favourite, menu);
return true;
}
public boolean onOptionsItemSelected(MenuItem item) {
//respond to menu item selection
switch (item.getItemId()) {
case R.id.favourite1:
//this is where shared prefrences is created?
return true;
default:
return super.onOptionsItemSelected(item);
My suggestion..
On clicking the fav icon:
get the name of the current activity and persist it.(db,sharedpref .. your choice).
Create a listView and an adapter for it, which fetches the activity name from the db or sharedPref.
Set click listener for the list view.
get the name of the clicked listview.
call an intent with the selected val.
My suggestion..
On clicking the fav icon:
get the name of the current activity and persist it.(db,sharedpref .. your choice).
Create a listView and an adapter for it, which fetches the activity name from the db or sharedPref.
Set click listener for the list view.
get the name of the clicked listview.
call an intent with the selected val.
EDIT:
Sharedpreference is one of the ways of persisting data in android.(others being database,file etc). The sharedPreference file stores in a key-value format.
Get an instance of the sharedpreference class and editor classs:
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
SharedPreferences.Editor editor = wmbPreference.edit();
Add values in the sharedPrefrence :
editor.putBoolean("key", value);
editor.putFloat("key1", value);
editor.putInt("key2", value);
editor.putLong("key3", value);
editor.putString("key4", value);
editor.putStringSet("key5", values);
Persist these inserted values:
editor.commit();
Now, these key-value pairs can be utilized from any activity:
Get an instance:
SharedPreferences wmbPreference = PreferenceManager.getDefaultSharedPreferences(getApplicationContext());
Get the value by passing the right key:
boolean boolValue= wmbPreference.getBoolean("key", true);
Thats it, as of sharedprefrence is concerned.

Hide button in ExpandableListView

I've just gotten an ExpandableListView setup and everything works fine so far. On the group/parent I have a TextView and and Button. The purpose of the list is to have people sample different sounds that are included in the app, and it they click the button then the sounds will be saved to the SD Card. Here's a link to what I have so far: http://imgur.com/djSCIrG
My question is whether or not it's possible that after someone clicks the button and chooses to purchase the pack if it's possible to hide just that one button and not all of the buttons in every group.
Here's is my main layout (expandablelistview_main.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent" >
<TextView
android:id="#+id/soundpacktitle"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginTop="#dimen/expandablelistview_main_soundpacktitle_topmargin"
android:layout_centerHorizontal="true"
android:text="#string/soundpacktitle"
android:textSize="#dimen/expandablelistview_main_soundpacktitle_textsize" />
<ExpandableListView
android:id="#+id/soundpacklist"
android:layout_width="fill_parent"
android:layout_height="0dp"
android:layout_below="#+id/soundpacktitle"
android:layout_above="#+id/soundpackbottombar"
android:layout_marginTop="#dimen/expandablelistview_main_soundpacklist_topmargin"
android:transcriptMode="disabled"
android:cacheColorHint="#00000000"
android:listSelector="#android:color/transparent" />
</RelativeLayout>
Here is my group/parent layout (expandablelistview_group.xml):
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="?android:attr/listPreferredItemHeight"
android:orientation="horizontal" >
<TextView
android:id="#+id/grouptextview"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:gravity="center_vertical"
android:layout_marginLeft="#dimen/expandablelistview_group_grouptextview_leftmargin"
android:textSize="#dimen/expandablelistview_group_grouptextview_textsize" />
<Button
android:id="#+id/buypackbutton"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="center_vertical"
android:layout_alignParentRight="true"
android:focusable="false"
android:focusableInTouchMode="false"
android:text="#string/buypack"
android:padding="#dimen/expandablelistview_group_buypackbutton_padding"
android:textSize="#dimen/expandablelistview_group_buypackbutton_textsize"
android:textStyle="bold" />
</RelativeLayout>
Here is my java class:
public class InAppSounds extends Activity {
private ExpandableListView soundpacklist;
private ArrayList<String> groups;
private ArrayList<ArrayList<ArrayList<String>>> childs;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.expandablelistview_main);
TextView soundpacktitle = (TextView) findViewById(R.id.soundpacktitle);
soundpacktitle.setTypeface(printbold);
// Declare the ExpandableListView and set's the indicator to the list arrows
soundpacklist = (ExpandableListView) findViewById(R.id.soundpacklist);
soundpacklist.setGroupIndicator(getResources().getDrawable(R.drawable.list_groupselector));
LoadData();
myExpandableAdapter adapter = new myExpandableAdapter(this, groups, childs);
soundpacklist.setAdapter(adapter);
}
// Loads the ExpandableListView with parent and children groups
private void LoadData() {
groups = new ArrayList<String>();
childs = new ArrayList<ArrayList<ArrayList<String>>>();
// String array that stores the parent and child names
String[] soundpackgroups = getResources().getStringArray(R.array.soundpackgroups);
String[] soundpack1 = getResources().getStringArray(R.array.soundpack1);
String[] soundpack2 = getResources().getStringArray(R.array.soundpack2);
String[] soundpack3 = getResources().getStringArray(R.array.soundpack3);
// First Sound Pack and their songs
groups.add(soundpackgroups[0]);
childs.add(new ArrayList<ArrayList<String>>());
for (int a = 0; a < soundpack1.length; a++) {
childs.get(0).add(new ArrayList<String>());
childs.get(0).get(a).add(soundpack1[a]);
}
// Second Sound Pack and their songs
groups.add(soundpackgroups[1]);
childs.add(new ArrayList<ArrayList<String>>());
for (int a = 0; a < soundpack2.length; a++) {
childs.get(1).add(new ArrayList<String>());
childs.get(1).get(a).add(soundpack2[a]);
}
// Third Sound Pack and their songs
groups.add(soundpackgroups[2]);
childs.add(new ArrayList<ArrayList<String>>());
for (int a = 0; a < soundpack3.length; a++) {
childs.get(2).add(new ArrayList<String>());
childs.get(2).get(a).add(soundpack3[a]);
}
}
public class myExpandableAdapter extends BaseExpandableListAdapter {
private final ArrayList<String> groups;
private final ArrayList<ArrayList<ArrayList<String>>> children;
private final Context context;
public myExpandableAdapter(Context context, ArrayList<String> groups,
ArrayList<ArrayList<ArrayList<String>>> children) {
this.context = context;
this.groups = groups;
this.children = childs;
}
#Override
public boolean areAllItemsEnabled() {
return true;
}
#Override
public ArrayList<String> getChild(int groupPosition, int childPosition) {
return children.get(groupPosition).get(childPosition);
}
#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) {
String child = getChild(groupPosition, childPosition).get(0);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.expandablelistview_child, null);
}
// TypeFace variable for the PrintBold
printbold = Typeface.createFromAsset(getAssets(), "fonts/PrintBold.otf");
TextView childtxt = (TextView) convertView.findViewById(R.id.childtextview);
childtxt.setTypeface(printbold);
childtxt.setText(child);
return convertView;
}
#Override
public int getChildrenCount(int groupPosition) {
return children.get(groupPosition).size();
}
#Override
public String getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
final String group = getGroup(groupPosition);
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.expandablelistview_group, null);
}
// TypeFace variable for the PrintBold
printbold = Typeface.createFromAsset(getAssets(), "fonts/PrintBold.otf");
TextView grouptxt = (TextView) convertView.findViewById(R.id.grouptextview);
grouptxt.setTypeface(printbold);
grouptxt.setText(group);
final Button buypackbutton = (Button) convertView.findViewById(R.id.buypackbutton);
buypackbutton.setClickable(true);
buypackbutton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View view) {
AlertDialog.Builder alert = new AlertDialog.Builder(InAppSounds.this);
if (group.equals("Pack #1")) {
alert.setCancelable(false);
alert.setTitle(getString(R.string.buypacktitle));
alert.setIcon(getResources().getDrawable(R.drawable.ic_audioicon));
alert.setMessage(getString(R.string.buypackmsg));
alert.setPositiveButton("Yes", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
// check to make sure the SD card is mounted
// if not display an AlertDialog
if (!isSDPresent()) {
sdcardalert();
}
else {
// this will erase the button in all the groups, not just this group
buypackbutton.setVisibility(View.INVISIBLE);
}
}
});
alert.setNegativeButton("No", new DialogInterface.OnClickListener() {
#Override
public void onClick(DialogInterface dialog, int which) {
dialog.cancel();
}
});
alert.show();
}
}
});
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
}
I would appreciate any guidance in this matter. Thanks
Yes. It's easy. All that you have to do is get a reference to your button and set the visibility to gone. Like this:
Button sampleButton = (Button) findViewById(R.id.sample_button);
sampleButton.setVisiblity(View.GONE);
Note: when you set it to View.GONE the layout space that was initially given to it is also removed. If you just want to remove the button and keep the layout space use
View.INVISIBLE instead.
EDIT: Here's how I would keep the button from reappearing: First, I would use a boolean to track the status of the button while the activity is active. Then in your override of getChildView I would check this boolean and set the visibility accordingly. Maybe insert something like this into the getChildView callback to keep the button from reappearing when the list item is clicked:
if (!showButton) {
Button button = (Button) findViewById(R.id.sample_button);
button.setVisibility(View.GONE);
}
As for coming back to the screen. To keep track of the whether not to show the button I would use a boolean and store it in SharedPreferences. Then, also in the getChildView callback, check the status of the boolean and set it accordingly. Something like this:
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
boolean showButtonStatusPref = settings.getBoolean("showButton", true);
if(!showButtonStatusPref) {
Button button = (Button) findViewById(R.id.sample_button);
button.setVisibility(View.GONE);
}
The only other thing you need to do is manage the status of each button.
EDIT 2: I completely overlooked the fact that the same layout is used for the child views (duh! brain cramp :)).
You could still use shared preferences to keep track of which samples have been downloaded (you could use Set for this). You would also need to create a way to assign "identifiers" to each sample. From there all that you would have to do is perform a check every time getChildView() is called and, if the Set contains the selected sample identifier, set the button visibility to gone. That should take care of showing the button when the sample hasn't been downloaded and not showing the button when the sample has been downloaded. Maybe something like this in the getChildView():
Set<String> defaultSet = new SortedSet<String>();
defaultSet.add("Nothing downloaded");
SharedPreferences settings = getSharedPreferences(PREFS_NAME, 0);
SortedSet<String> listOfDowloaded = settings.getStringSet("isDownloadedList", );
if (listOfDownLoaded.contains(sampleDownloadIdentifier)) {
Button button = (Button) findViewById(R.id.some_id);
button.setVisiblity(View.GONE);
}

Centering the clicked item in listview in Android

I have a list view in left of the screen and on click of the item i want to update a text on the right half of the screen, what i want to do here is that to move the clicked item in center of the listview. Like if the item is on top and i click on it it automatically moves to the center of the list view, how I can do this? Any kind of help will be appreciated.
I have a listview in which 7 items are visible and on startup 4th item will be selected as this is in center of the visible items in listview and if there are n items and whichever item is selected by user will be in center of the visible items in listview. Like i have 10 items and on start 4th is selected and when user selects the 3rd item, nth item from listview should come to index zero and and 3rd will come to position 4. Similarly for every other selected item? Can any one provide a code snippet for this?
Change items order in ListView source Array and then call notifyDataSetChanged() in ListView Adapter
EDIT: Code sample
public class ListAdapter extends BaseAdapter{
private Activity activity;
private ArrayList<ListRowObject> listItems;
public ListAdapter(Activity activity){
this.activity = activity;
listItems = new ArrayList<ListRowObject>();
}
public void addItem(ListRowObject item){
listItems.add(item);
notifyDataSetChanged();
}
public void addItems(ArrayList<ListRowObject> items){
listItems = items;
notifyDataSetChanged();
}
public void clear(){
listItems = null;
listItems = new ArrayList<ListRowObject>();
notifyDataSetChanged();
}
#Override
public int getCount() {
return listItems.size();
}
#Override
public Object getItem(int position) {
return listItems.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup viewGroup) {
ViewHolder holder;
if(convertView == null){
holder = new ViewHolder();
convertView = activity.getLayoutInflater().inflate(R.layout.list_row, null);
holder.text = (TextView) convertView.findViewById(R.id.text);
holder.bgLayout = (LinearLayout) convertView.findViewById(R.id.bgLayout);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
ListRowObject row = listItems.get(position);
if(row.isSelected())
holder.bgLayout.setBackgroundColor(Color.GRAY);
else
holder.bgLayout.setBackgroundColor(Color.WHITE);
holder.text.setText(row.getText());
return convertView;
}
}
//--------
public class ListRowObject {
private String text;
private int positionInList;
private boolean isSelected;
public String getText() {
return text;
}
public void setText(String text) {
this.text = text;
}
public int getPositionInList() {
return positionInList;
}
public void setPositionInList(int positionInList) {
this.positionInList = positionInList;
}
public boolean isSelected() {
return isSelected;
}
public void setSelected(boolean selected) {
isSelected = selected;
}
}
//------
public class Main extends Activity {
private ListView listView;
private ListAdapter adapter;
private Activity activity;
private ArrayList<ListRowObject> items;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
activity = this;
initializeFormViews();
initializeOnClickEvents();
fillList();
}
private void initializeFormViews(){
listView = (ListView) findViewById(R.id.listView);
}
private void initializeOnClickEvents(){
listView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
Toast.makeText(activity, "Pressed " +position, Toast.LENGTH_SHORT).show();
// unselect all rows
for(ListRowObject item : items){
item.setSelected(false);
}
int first = adapterView.getFirstVisiblePosition();
int last = adapterView.getLastVisiblePosition();
int centerPosition = (first + last) / 2;
// change bg for centerPosition row
adapterView.getChildAt(centerPosition).findViewById(R.id.bgLayout).setBackgroundColor(Color.GRAY);
changeItems(position, centerPosition);
}
});
}
private void changeItems(int pressedPosition, int centerPosition){
ListRowObject centerRow = items.get(centerPosition);
ListRowObject pressedRow = items.get(pressedPosition);
pressedRow.setSelected(true);
centerRow.setSelected(false);
items.remove(centerPosition);
items.add(centerPosition, pressedRow);
items.remove(pressedPosition);
items.add(pressedPosition, centerRow);
adapter.clear();
adapter.addItems(items);
}
private void fillList(){
adapter = new ListAdapter(activity);
items = new ArrayList<ListRowObject>();
items = getItems();
for(ListRowObject item : items){
adapter.addItem(item);
}
listView.setAdapter(adapter);
}
private ArrayList<ListRowObject> getItems(){
ArrayList<ListRowObject> result = new ArrayList<ListRowObject>();
for(int i = 0; i < 15; i++){
ListRowObject object = new ListRowObject();
object.setPositionInList(i);
object.setText("Item #" + i);
if(i != 4)
object.setSelected(false);
else
object.setSelected(true);
result.add(object);
}
return result;
}
}
//------
public class ViewHolder {
public TextView text;
public LinearLayout bgLayout;
}
list_row.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/bgLayout">
<TextView
android:layout_width="match_parent"
android:layout_height="50dp"
android:id="#+id/text"
android:textColor="#000000"
android:textSize="24dp"
android:gravity="center"/>
</LinearLayout>
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="match_parent"
android:layout_height="match_parent">
<ListView
android:layout_width="match_parent"
android:layout_height="match_parent"
android:id="#+id/listView"/>
</LinearLayout>
when you create ArrayAdapter for your listview you send a ListArray to it.when you want change content .you only change this listArray then when click your item you can change ListArray and call notifyDataSetChanged(); method your adapter.

Multiple selection in custom ListView with CAB

After reading and try'n'error for days, I´m giving up and ask for help.
< edit >
I am using ActionBarSherlock.
< /edit >
What I want to achieve:
A ListView with a custom layout for each row, where the user can select multiple list items.
A selected list item should have a different background color. When there is at least one item selected, a contextual action bar (CAB) should be shown.
It should look more or less like the multiple selection of emails in the GMail app. The only difference is that in the gmail app the selection is done by clicking the checkbox of a row, whereas I don´t want to have a checkbox, but a row should be selected no matter, where the user clicks.
What I tried:
Following this tutorial, using a Checkable row layout with some logic to change the background color when the check state was toggled, I got everything working except that I could not register a click listener like OnItemClickListener on the ListView to show the CAB. Neither providing a click listener for each row View helped because this prevented to change the background color of the selected items.
I also tried adding a MultiChoiceModeListener to the ListView like that
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
listView.setMultiChoiceModeListener(new MultiChoiceModeListener() { //.. });
With the same result, no background color change.
What I am looking for: A hint or a tutorial or sample code how to do this. If you need some code snippets to help, let me know.
See if the code helps you(it's basically a ListActivity with a custom adapter to hold the status of checked items(+ different background)):
public class CABSelection extends ListActivity {
private ArrayList<String> mItems = new ArrayList<String>();
private SelectionAdapter mAdapter;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
for (int i = 0; i < 24; i++) {
mItems.add("Name" + i);
}
// R.layout.adapters_cabselection_row is a LinearLayout(with green
// background(#99cc00)) that wraps an ImageView and a TextView
mAdapter = new SelectionAdapter(this,
R.layout.adapters_cabselection_row, R.id.the_text, mItems);
setListAdapter(mAdapter);
getListView().setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
getListView().setMultiChoiceModeListener(new MultiChoiceModeListener() {
private int nr = 0;
#Override
public boolean onCreateActionMode(ActionMode mode, Menu menu) {
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.cabselection_menu, menu);
return true;
}
#Override
public boolean onPrepareActionMode(ActionMode mode, Menu menu) {
return false;
}
#Override
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
StringBuilder sb = new StringBuilder();
Set<Integer> positions = mAdapter.getCurrentCheckedPosition();
for (Integer pos : positions) {
sb.append(" " + pos + ",");
}
switch (item.getItemId()) {
case R.id.edit_entry:
Toast.makeText(CABSelection.this, "Edited entries: " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.delete_entry:
Toast.makeText(CABSelection.this, "Deleted entries : " + sb.toString(),
Toast.LENGTH_SHORT).show();
break;
case R.id.finish_it:
nr = 0;
mAdapter.clearSelection();
Toast.makeText(CABSelection.this, "Finish the CAB!",
Toast.LENGTH_SHORT).show();
mode.finish();
}
return false;
}
#Override
public void onDestroyActionMode(ActionMode mode) {
nr = 0;
mAdapter.clearSelection();
}
#Override
public void onItemCheckedStateChanged(ActionMode mode,
int position, long id, boolean checked) {
if (checked) {
nr++;
mAdapter.setNewSelection(position, checked);
} else {
nr--;
mAdapter.removeSelection(position);
}
mode.setTitle(nr + " rows selected!");
}
});
}
#Override
protected void onListItemClick(ListView l, View v, int position, long id) {
l.setItemChecked(position, !mAdapter.isPositionChecked(position));
}
private class SelectionAdapter extends ArrayAdapter<String> {
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
public SelectionAdapter(Context context, int resource,
int textViewResourceId, List<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(Color.parseColor("#99cc00")); //default color
if (mSelection.get(position) != null) {
v.setBackgroundColor(Color.RED);// this is a selected position so make it red
}
return v;
}
}
}
The R.layout.adapters_cabselection_row is a custom layout for the row(a very simple one) with a green background:
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:background="#99cc00" >
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/ic_launcher" />
<TextView
android:id="#+id/the_text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:textColor="#ffffff"
android:textSize="17sp"
android:textStyle="bold" />
</LinearLayout>
R.menu.cabselection_menu is a menu file with 3 options(edit, delete, finish the CAB) which don't do anything except pop a Toast with a message regarding the rows selected:
<?xml version="1.0" encoding="utf-8"?>
<menu xmlns:android="http://schemas.android.com/apk/res/android" >
<item
android:id="#+id/edit_entry"
android:icon="#android:drawable/ic_menu_edit"
android:title="Edit!"/>
<item
android:id="#+id/delete_entry"
android:icon="#android:drawable/ic_menu_delete"
android:title="Delete!"/>
<item
android:id="#+id/finish_it"
android:icon="#android:drawable/ic_menu_crop"
android:title="Get me out!"/>
</menu>
I think the easiest way is to apply
android:background="android:attr/activatedBackgroundIndicator"
To which ever layout is the one you will be clicking.
This highlights the layout when selected using
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE_MODAL);
worked for me anyway
Using ActionBarSherlock the MultiChoiceModeListener used in Luksprog´s answer is not yet available if you want to support API level < 11.
A workaround is to use the onItemClickListener.
List setup:
listView = (ListView) timeline.findViewById(android.R.id.list);
listView.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
listView.setItemsCanFocus(false);
listView.setAdapter(new ListAdapter(getActivity(), R.layout.cleaning_list_item, items));
Listener of ListFragment or ListActivity:
#Override
public void onListItemClick(ListView l, View v, int position, long id) {
SparseBooleanArray checked = listView.getCheckedItemPositions();
boolean hasCheckedElement = false;
for (int i = 0; i < checked.size() && !hasCheckedElement; i++) {
hasCheckedElement = checked.valueAt(i);
}
if (hasCheckedElement) {
if (mMode == null) {
mMode = ((SherlockFragmentActivity) getActivity()).startActionMode(new MyActionMode());
mMode.invalidate();
} else {
mMode.invalidate();
}
} else {
if (mMode != null) {
mMode.finish();
}
}
}
Where MyActionMode is an implementation of ActionMode.Callback:
private final class MyActionMode implements ActionMode.Callback { /* ... */ }

Categories

Resources