Android how to identify item in listview with checkbox - android

I am really stuck here. What I want is not simple (for me), however I've been programming android a year now.
What I want is a listview with an imageview, a textview, a checkbox, and another textview in each row.
Let's have a textview and a checkbox first in the layout.
Based on this tutorial I managed to do that (there are a lot, but this seems to be the best for me). I have a listview populated with textviews and checkboxes.
This is the result:
This is how I get the text of textview I click on:
textView.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
TextView tv = (TextView) v ;
String text_of_clicked_textview = tv.getText().toString();
Log.i("TAG", "" + text_of_clicked_textview);
}
});
So When I click on Mercury, I get Mercury in the text_of_clicked_textview variable.
But how can i check which checkbox I clicked on? E.g I click on the 3rd checkbox, I want to now it is in the row of Earth. Best would be if I get to know both the text of textview in the row of the listview(Earth) and and number of the item (3).
I guess I have to set an onClickListener on the checkbox but what next?
checkBox.setOnClickListener( new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v ;
}
});

This is XML for Custom Row in ListView :
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ImageView
android:id="#+id/imageView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/camera_icon" />
<TextView
android:id="#+id/textView1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Large Text"
android:textAppearance="?android:attr/textAppearanceLarge" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text=""
/>
</LinearLayout>
This is Complete Activity in which List is implemented :
Just Copy this Activity for test then understand code. Place one listview in main Activity
package com.DemoTest;
import java.util.ArrayList;
import java.util.List;
import java.util.zip.Inflater;
import android.app.Activity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;
public class CustomList extends Activity implements OnClickListener
{
ListView listView;
ArrayList<EachRow> list=new ArrayList<CustomList.EachRow>();
EachRow each;
#Override
protected void onCreate(Bundle savedInstanceState)
{
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
String[] color={"red","green","blue","white","yellow","cyan","purple","grey",
"0red","0green","0blue","0white","0yellow","0cyan","0purple","0grey",
"1red","1green","1blue","1white","1yellow","1cyan","1purple","1grey"};
for(String str : color)
{
each=new EachRow();
each.text=str;
list.add(each);
}
listView=(ListView)findViewById(R.id.listView1);
listView.setAdapter(new MyAdapter(this, 0, list));
//listView.setOnItemClickListener(this);
}
class MyAdapter extends ArrayAdapter<EachRow>
{
LayoutInflater inflat;
ViewHolder holder;
public MyAdapter(Context context, int textViewResourceId,
ArrayList<EachRow> objects)
{
super(context, textViewResourceId, objects);
// TODO Auto-generated constructor stub
inflat=LayoutInflater.from(context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
if(convertView==null)
{
convertView=inflat.inflate(R.layout.row_checkox, null);
holder=new ViewHolder();
holder.textView=(TextView)convertView.findViewById(R.id.textView1);
holder.image=(ImageView)convertView.findViewById(R.id.imageView1);
holder.check=(CheckBox)convertView.findViewById(R.id.checkBox1);
holder.check.setOnClickListener(CustomList.this);
convertView.setTag(holder);
}
holder=(ViewHolder) convertView.getTag();
EachRow row= getItem(position);
Log.d("size", row.text);
holder.textView.setText(row.text);
holder.check.setChecked(row.checkBool);
holder.check.setTag(position);
return convertView;
}
#Override
public EachRow getItem(int position) {
// TODO Auto-generated method stub
return list.get(position);
}
private class ViewHolder
{
TextView textView;
ImageView image;
CheckBox check;
}
}
private class EachRow
{
String text;
boolean checkBool;
}
#Override
public void onClick(View v)
{
// TODO Auto-generated method stub
EachRow row=list.get((Integer)v.getTag());
row.checkBool=!row.checkBool;
Log.d("item", "Item Click at "+(Integer)v.getTag()+" : "+row.text+" is "+row.checkBool);
}
}

Better than adding an onClickListener to each checkbox, you could also use an ItemClickListener on your list.
Refer to this post to find out the row that has been clicked :
onItemClick <string-array> strings.xml (not ListView/ArrayList)
There are other options, but it involves creating a custom row widget class, and passing it its row position when your adapter creates or updates it.

you would have to have a onTouchListener on the container that holds all of them and make sure that you return false on your listeners so that they don't consume the event. onClickListener consumes it automatically.

If you only concerned with text and checkbox then you can use this
In XML :
<ListView
android:id="#+id/listViewCursor"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:choiceMode="multipleChoice" >
String[] color={"red","green","blue","white","yellow","cyan","purple","grey"};
list.setAdapter(new ArrayAdapter<String>(this, android.R.layout.simple_list_item_multiple_choice, color));
ANd on some event check which checkboxes are selected.
SparseBooleanArray boolArray=list.getCheckedItemPositions();
int size=list.getCount();
for(int i=0;i<size;i++)
{
if(boolArray.valueAt(i)==true)
{
Log.d("size", color[i]);
}
}

Related

Android - OnItemClickListener dont't capture event click in adapterview

I have an activity that has a AdapterView to display a gridview of ImageView
The Activity:
package com.xlck.mislistas
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import com.actionbarsherlock.app.ActionBar;
import com.actionbarsherlock.app.SherlockActivity;
import com.xlck.mislistas.adapters.ExpandableHeightGridView;
import com.xlck.mislistas.adapters.ImageGridAdapter;
import com.xlck.mislistas.adapters.ImageGridAdapter.ViewHolder;
import com.xlck.mislistas.adapters.ImageGridBean;
public class AmigosActivity extends SherlockActivity {
...
private ExpandableHeightGridView gridViewImagenes;
gridViewImagenes = (ExpandableHeightGridView) findViewById(R.id.grvImagenes);
// Adapter GridView
gridViewImagenes.setAdapter(imageGridAdapter);
gridViewImagenes.setExpanded(true);
.
.
.
// Listener
gridViewImagenes.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
Do something ...;
}
});
}
The Adapter:
package com.xlck.mislistas.adapters;
import java.util.ArrayList;
import java.util.List;
import android.app.Activity;
import android.content.Context;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.TextView;
import com.xlck.mislistas.R;
public class ImageGridAdapter extends BaseAdapter {
private Context mContext;
private List<ImageGridBean> items;
// Constructor
public ImageGridAdapter(Context context, ArrayList<ImageGridBean> items) {
this.mContext = context;
this.items = items;
}
#Override
public int getCount() {
return items.size();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
ImageGridBean item = (ImageGridBean) items.get(position);
LayoutInflater mInflater = (LayoutInflater) mContext
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
convertView = mInflater.inflate(R.layout.item_grid_imagen, null);
holder = new ViewHolder();
holder.txtId = (TextView) convertView.findViewById(R.id.uid);
holder.txtNombre = (TextView) convertView
.findViewById(R.id.txtNombre);
holder.imagen = (ImageView) convertView
.findViewById(R.id.imgImagen);
holder.check = (CheckBox) convertView.findViewById(R.id.chkItem);
holder.txtFondoNombre = (TextView) convertView.findViewById(R.id.txtFondoNombre);
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.txtId.setText(item.getId());
holder.txtNombre.setText(item.getNombre());
holder.imagen.setImageBitmap(item.getImagen());
if (item.getId().equals("0"))
holder.check.setVisibility(View.INVISIBLE);
return convertView;
}
#Override
public ImageGridBean getItem(int position) {
return items.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
// --------------------------------------------------------< ViewHolder >---
// -------------------------------------------------------------------------
/* private view holder class */
public class ViewHolder {
public TextView txtId;
public TextView txtNombre;
public TextView txtFondoNombre;
public ImageView imagen;
public CheckBox check;
}
}
I have this Layout:
<?xml version="1.0" encoding="utf-8"?>
<RelativeLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/relativeLayout1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:descendantFocusability="blocksDescendants" >
<RelativeLayout
android:id="#+id/relativeLayout2"
android:layout_width="92dp"
android:layout_height="92dp"
android:layout_alignParentBottom="false"
android:layout_alignParentLeft="false" >
<TextView
.../>
<ImageView
.../>
<TextView
.../>
<TextView
... />
</RelativeLayout>
<LinearLayout
android:layout_width="38dp"
android:layout_height="32dp"
android:layout_alignRight="#+id/relativeLayout2"
android:layout_alignTop="#+id/relativeLayout2"
android:layout_marginRight="0dp"
android:layout_marginTop="4dp" >
<CheckBox
android:id="#+id/chkItem"
android:layout_width="wrap_content"
android:layout_height="wrap_content" />
</LinearLayout>
</RelativeLayout>
Well, if i click in ImageView, it fire the event click and the listener capture it, but if i click in CheckBox the event click don't fire.
What I doing wrong? What I need to do?
Thanks in advance.
android:focusableInTouchMode="false" android:focusable="false"
#Sam is right, checkboxes handle clicks on their own and the click event never reaches the AdapterView.
Now, technically speaking, you could set android:clickable="false" for your checkbox in the layout file, and then the click event would get delivered up the view hierarchy, but in this case you won't be able to do anything useful with the checkbox, it will just always stay unchecked.
Here's what would be a better approach. Move the "do something" into a different method and add another onClickListener for the checkbox, to do the same thing:
gridViewImagenes.setOnItemClickListener(new OnItemClickListener() {
public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
doSomething();
}
});
myCheckbox.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View view) {
doSomething();
}
});
}
private void doSomething() {
//Do Stuff
}
Think you will have to implement a OnCheckedChangelistener to the checkbox, in your case to chkItem.
See CompoundButton.OnCheckedChangeListener
The implementation would be something like...
CheckBox checkBox = (CheckBox) findViewById(R.id.chkItem);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked) {
// checkbox is checked - doSomething()
} else {
// checkbox is unchecked
}
}
});
Hope this helps.
I finally decided to put the adapter into the Activity class. In Class Adapter put a listener both ImageView and CheckBox component, since these listener invoking a method of the Activity class.
Thanks to all for your time and response!!!

Android checkbox issue in custom list item view

Please forgive me for what may sound like a newbie question as I am just getting started
with Android.
What I am attempting to accomplish is creating a custom list Item layout that contains 2 textViews and a checkbox for selecting multiple items. The problem is the checkboxes are
"extra" selecting list items, (example) if I select #1 then #9 and # 18 selects as well.
as if the checkBox instances are recycling themselves or maybe sharing the same listener IDs
if that even makes sense. Ive narrowed my code to the primary components for simplicity. Any suggestions would be dearly appreciated.
package com.untame.mobile.app;
import java.text.ChoiceFormat;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import android.app.Activity;
import android.app.ListActivity;
import android.content.Context;
import android.os.Bundle;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.ArrayAdapter;
import android.widget.BaseAdapter;
import android.widget.CheckBox;
import android.widget.ListView;
import android.widget.SimpleAdapter;
import android.widget.TextView;
import com.untame.mobile.app.*;
public class TestList extends ListActivity {
ArrayList<Map<String, String>> artistList;
private static String TAG = "TESTLIST!";
ListView listv;
LayoutInflater mInflater;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.testlayout);
mInflater = (LayoutInflater) getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
artistList = new ArrayList<Map<String, String>>();
for(Integer loop = 0 ;loop < 21;loop++){
String loopI = loop.toString();
Map<String,String> hm = new HashMap<String, String>();
hm.put("artist", loopI);
hm.put("count", loopI);
artistList.add(hm);
}
// Loading artistNames in Background Thread
// new LoadArtistList().execute("extra_tracks");
listv = (ListView) getListView();
listv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
// listv.setItemsCanFocus(false);
final class MyListAdapter extends BaseAdapter{
ArrayList<Integer> ids;
public MyListAdapter(Context context) {
ids = new ArrayList<Integer>();
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
final ViewHolder holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.testlistitem1, null, false);
convertView.setClickable(true);
holder = new ViewHolder(getApplicationContext());
holder.choose = (CheckBox) convertView.findViewById(R.id.testcheckBox1);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
return convertView;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return artistList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return artistList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return 0;
}
}
MyListAdapter adapter = new MyListAdapter(this);
setListAdapter(adapter);
}
}
ViewHolder.java
package com.untame.mobile.app;
import android.content.Context;
import android.view.View;
import android.widget.CheckBox;
import android.widget.TextView;
public class ViewHolder extends View {
public ViewHolder(Context context) {
super(context);
}
public CheckBox remove;
public CheckBox choose;
public TextView text2;
public TextView text1;
}
testlayout.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/rootLayout"
android:layout_width="wrap_content"
android:layout_height="match_parent" >
<ListView
android:id="#android:id/list"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
testitem.xml
<?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:orientation="vertical" >
<com.untame.mobile.app.ArtistListCheckBox
android:id="#+id/testcheckBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="choose"
/>
</LinearLayout>
Solved!!! It appears after much trial and error, that one must store the actual checkbox information (ie : checkbox.isChecked) into a seperate object that can be stored as a tag inside the current checkbox. This way when the view redraws the new items as you scroll the
list the newly created checkbox can recapture its last state from the object it was stored in.
In my case, I have a list of Music Artists in the list so I created an Artist.java class
to create Artist objects to store as checkbox tags.

How to maintain the clicked item highlighted in Listview?

I need to make a listview keep the selected view highlighted until another item is chosen, in that case the previous view removes the highlight and the latest clicked gets the highlight.
I tried not to do this and with a radio button but it isnt working.
It's actually pretty easy:
In the custom layout for the individual listview item, make sure it has the attribute:
android:background="?android:attr/activatedBackgroundIndicator" >
By way of example, here's a listview item layout from the HoneycombGallery sample that ships with the SDK (located in the title_list_item.xml file:
<TextView xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="10dp"
android:gravity="bottom"
android:textAppearance="?android:attr/textAppearanceMedium"
android:background="?android:attr/activatedBackgroundIndicator" >
</TextView>
That attribute will cause the background color to change based on whether the individual list item is selected or not.
i m novice to android so i found this question interesting and finally i succeeded after 1 and half hour ;-)
here is the code:
main.xml
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
android:orientation="vertical" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content" >
</ListView>
</LinearLayout>
listinflater.xml
android:id="#+id/tvItem"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:text="TextView" />
PreservelistitemActivity.java
package com.mehuljoisar;
import android.app.Activity;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.AdapterView.OnItemClickListener;
public class PreservelistitemActivity extends Activity {
//declaring variable
ListView listView1;
MyAdapter adapter1;
Integer length,i;
String[] data = {"Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh","Mehul","Milind","Aamir","Amitabh"};
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
//binding to the view
listView1 = (ListView)findViewById(R.id.listView1);
//set adapter
adapter1=new MyAdapter(PreservelistitemActivity.this,data);
listView1.setAdapter(adapter1);
}
public class MyAdapter extends BaseAdapter{
private final Activity context;
private final String[] data;
public MyAdapter(Activity context,
String[] data) {
// TODO Auto-generated constructor stub
super();
this.context=context;
this.data=data;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return data.length;
}
#Override
public Object getItem(int arg0) {
// TODO Auto-generated method stub
return null;
}
#Override
public long getItemId(int arg0) {
// TODO Auto-generated method stub
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
LayoutInflater inflater = context.getLayoutInflater();
convertView = inflater.inflate(R.layout.listinflater, null);
final TextView tvItem = (TextView)convertView.findViewById(R.id.tvItem);
tvItem.setText(data[position]);
listView1.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View v,
int position, long id) {
/* length=parent.getAdapter().getCount();
for(i=0;i<length;i++)
{
//clear
if(i==position)
{
//set
}
}
*/
v.setSelected(true);
}
});
return convertView;
}
}
}

need help for on click listener for android custom ListView

my app has custom ListView, each row contains checkbox ,edit text and 2 buttons. In the main xml layout file i have 1 submit button and listView. i want that, when i click on submit button, i should get all checked row position.I am new to android programming ,so plz help me my code is not working here is my code:
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">
<Button android:layout_height="wrap_content"
android:text="#string/button_submit"
android:layout_width="wrap_content"
android:id="#+id/main_submit_button" android:onClick="#string/button_submit"></Button>
<ListView
android:id="#+id/list_view"
android:layout_width="fill_parent"
android:layout_height="fill_parent"
/>
</LinearLayout>
items.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="wrap_content">
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<TextView
android:layout_height="wrap_content"
android:layout_width="fill_parent" android:layout_weight="1"
android:id="#+id/items_name"
android:gravity="left"
android:textStyle="bold" />
<CheckBox android:id="#+id/items_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="right"
/>
</LinearLayout>
<LinearLayout android:layout_height="wrap_content"
android:layout_width="fill_parent">
<Button android:id="#+id/items_add_button"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:gravity="left"
android:text="#string/text_switcher_plus" />
<EditText android:digits="10"
android:textStyle="bold" android:gravity="left"
android:id="#+id/items_plates" android:layout_height="wrap_content"
android:layout_width="90dp"></EditText>
<Button android:layout_height="wrap_content"
android:layout_width="wrap_content"
android:id="#+id/items_minus_button"
android:text="#string/text_switcher_minus"
android:gravity="right"
/>
</LinearLayout>
</LinearLayout>
VegmenuActivity
package com.sagar.resmenu;
import java.util.ArrayList;
import java.util.Arrays;
import android.app.Activity;
import android.os.Bundle;
import android.util.Log;
import android.util.SparseBooleanArray;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.Button;
import android.widget.ListView;
// reference:http://pareshnmayani.wordpress.com/tag/android-custom-listview-example
public class VegmenuActivity extends Activity implements OnItemClickListener{
//dynamic array that contains names of items
private ArrayList<String> items = new ArrayList<String>
(Arrays.asList("Veg pulav", "Pav bhaji", "Panir tikka", "veg kolhapuri",
"Coconut Rice", "Curd rice", "Mint Pulao",
"Banana Custard","Basundi", "Cheese potato Tikkis",
"Dum aloo"));
private ArrayList<Integer> counter = new ArrayList<Integer>
(Arrays.asList(0, 0,0, 0, 0,0, 0,0, 0,0,0));
private SparseBooleanArray a;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
final ListView lv =(ListView)findViewById(R.id.list_view);
// lv.setOnClickListener(null);
MyAdapter adapter = new MyAdapter(getApplicationContext(),items,counter);
lv.setAdapter(adapter);
lv.setItemsCanFocus(false);
lv.setChoiceMode(ListView.CHOICE_MODE_MULTIPLE);
Button submit1;
submit1 = (Button)findViewById(R.id.main_submit_button);
submit1.setOnClickListener(new OnClickListener()
{
#Override
public void onClick(View v)
{
a = new SparseBooleanArray();
a.clear();
a = lv.getCheckedItemPositions();
int len = items.size();
for (int i = 0; i < len; i++)
{
if(a.valueAt(i) == true)
Log.d("Returned ", String.valueOf(a.valueAt(i)));
}
}
});
}
//private OnItemClickListener selectCat = new OnItemClickListener();
public void onItemClick(AdapterView<?> a, View v, int positon, long id) {
// TODO Auto-generated method stub
}
}
MyAdapter.java
package com.sagar.resmenu;
import java.util.ArrayList;
import android.content.Context;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.EditText;
import android.widget.TextSwitcher;
import android.widget.TextView;
public class MyAdapter extends BaseAdapter implements OnClickListener{
private LayoutInflater inflater;
private ArrayList<String> data;
VegmenuActivity m;
private ArrayList<Integer> counter;
public MyAdapter(Context context, ArrayList<String> data,ArrayList<Integer> counter) {
// TODO Auto-generated constructor stub
super();
// Caches the LayoutInflater for quicker use
this.inflater = (LayoutInflater)context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Sets the events data
this.data= data;
this.counter=counter;
}
public int getCount() {
return this.data.size();
//return this.counter.size();
}
public String getItem(int position) throws IndexOutOfBoundsException{
return null;
}
public long getItemId(int position) throws IndexOutOfBoundsException{
return 0;
}
public int getViewTypeCount(){
return 1;
}
public static class ViewHolder
{
TextView items_name;
CheckBox items_check ;
Button items_plus_button;
Button items_minus_button;
EditText plates;
}
public View getView(int position, View convertView, ViewGroup parent){
//String myText = getItem(position);
ViewHolder holder;
if(convertView == null){ // If the View is not cached
// Inflates the Common View from XML file
holder = new ViewHolder();
convertView = this.inflater.inflate(R.layout.items,parent,false);
holder.items_name = (TextView) convertView.findViewById(R.id.items_name);
holder.plates = (EditText) convertView.findViewById(R.id.items_plates);
holder.items_check = (CheckBox) convertView.findViewById(R.id.items_check);
convertView.setTag(holder);
}
else
holder=(ViewHolder)convertView.getTag();
holder.items_name.setText(data.get(position));
holder.plates.setText(String.valueOf(counter.get(position)));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
when I need check boxes inside listview, I often code as following:
MyAdapter.java:
- Declare an boolean array to mark which item is checked/unchecked:
....
boolean[] checked;
...
inside constructor:
checked = new boolean[data.size()];
- Inside getView()
{
.....
holder.items_check.setChecked(checked[position]);
holder.items_check.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
checked[position] = isChecked;
}
});
.....
- And method to get all checked items:
boolean[] getCheckedItems() {
return checked;
}
That's !
Could it be that your getItem and getItemId only return null and 1? These methods need to return the correct data for this to work I believe. getItem would need to be:
String getItem(int position)
{
return data.get(position);
}
and getItemId would simply return position instead of 0:
String getItemId(int position)
{
return position;
}

need tutorials on Android Custom-List

last days I was browsing one of the apps in Android
and I found out an amazing list.
I Found that Custom ListView Interesting.
When we click on the Text it shows me some Activity and when we click on the Arrow on Right it shows me a dialog.
I want to learn this. Can anybody go through some Tutorials where this Custom List is explained. Please Friends. guide me.. Thanks alot
Hi Below Is Custom ListView Example
First Create test.Java File below is code
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.os.Bundle;
import android.widget.ListView;
public class test extends Activity {
/** Called when the activity is first created. */
ArrayList<String> arrayString = new ArrayList<String>();
test_adapter adapter;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
arrayString.add("TextView1");
arrayString.add("TextView2");
arrayString.add("TextView3");
arrayString.add("TextView4");
arrayString.add("TextView5");
ListView list = (ListView) findViewById(R.id.LIST);
adapter = new test_adapter(this, arrayString);
list.setAdapter(adapter);
}
}
Also Used below Class file test_adapter.java
package com.test;
import java.util.ArrayList;
import android.app.Activity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.View.OnClickListener;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.RelativeLayout;
import android.widget.TextView;
import android.widget.Toast;
public class test_adapter extends BaseAdapter {
private Activity activity;
ArrayList<String> data = new ArrayList<String>();
private static LayoutInflater inflater = null;
public test_adapter(Activity a, ArrayList<String> d) {
activity = a;
data = d;
inflater = LayoutInflater.from(activity);
}
public int getCount() {
return data.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
public static class ViewHolder {
public TextView txt1;
public Button btn1;
public RelativeLayout rel1;
}
public View getView(int position, View convertView, ViewGroup parent) {
View vi = convertView;
final ViewHolder holder;
if (convertView == null) {
vi = inflater.inflate(R.layout.listview, null);
holder = new ViewHolder();
holder.txt1 = (TextView) vi.findViewById(R.id.txt1);
holder.btn1 = (Button) vi.findViewById(R.id.btn1);
holder.rel1 = (RelativeLayout) vi.findViewById(R.id.rel1);
vi.setTag(holder);
} else
holder = (ViewHolder) vi.getTag();
holder.txt1.setText(data.get(position));
holder.rel1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast
.makeText(activity, "Click On TextView",
Toast.LENGTH_LONG).show();
}
});
holder.btn1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast.makeText(activity, "Click On Button", Toast.LENGTH_LONG)
.show();
}
});
return vi;
}
}
Used below layout files main.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="fill_parent">
<ListView android:layout_width="fill_parent" android:id="#+id/LIST"
android:layout_height="fill_parent" />
</LinearLayout>
Used listview.xml file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent" android:layout_height="wrap_content"
android:orientation="horizontal">
<RelativeLayout android:id="#+id/rel1" android:layout_width="wrap_content"
android:layout_height="wrap_content">
<TextView android:layout_width="wrap_content"
android:layout_height="wrap_content" android:id="#+id/txt1"
android:text="Test Description"></TextView>
</RelativeLayout>
<RelativeLayout android:layout_width="fill_parent"
android:layout_height="wrap_content">
<Button android:id="#+id/btn1" android:layout_width="wrap_content"
android:layout_height="wrap_content" android:text="ClickHere"
android:layout_alignParentRight="true"></Button>
</RelativeLayout>
</LinearLayout>
Used Above Code and you will get display toast message and you can changed as per you requirement.

Categories

Resources