ListView remove only last items - android

I have List view with custom adapter and I have problem with removing items from list. Here is definition of list row
<?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:descendantFocusability="blocksDescendants">
<CheckBox
android:id="#+id/history_list_check"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_marginLeft="4dp"
android:layout_marginRight="10dp"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"/>
<TextView
android:id="#+id/history_list_label"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
android:layout_toRightOf="#id/history_list_check"/>
<ImageView
android:id="#+id/history_list_image"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_alignParentRight="true"
android:contentDescription="#string/history_drunk_image_description"
android:layout_alignParentBottom="true"
android:layout_alignParentTop="true"
/>
</RelativeLayout>
My custom adapter:
public class HistoryArrayAdapter extends ArrayAdapter<Measure> {
private final List<HistoryRowModel> list;
private final Activity context;
public HistoryArrayAdapter(Activity context, List<Measure> list) {
super(context, R.layout.history_list_row, list);
this.context = context;
this.list = new ArrayList<HistoryRowModel>();
for(Measure measure : list) {
HistoryRowModel rowModel = new HistoryRowModel(measure);
this.list.add(rowModel);
}
}
static class ViewHolder {
protected CheckBox checkbox;
protected TextView text;
protected ImageView imageView;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.history_list_row, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.history_list_check);
viewHolder.checkbox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
HistoryRowModel element = (HistoryRowModel) viewHolder.checkbox.getTag();
element.setSelected(buttonView.isChecked());
}
});
viewHolder.text = (TextView) view.findViewById(R.id.history_list_label);
viewHolder.imageView = (ImageView) view.findViewById(R.id.history_list_image);
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.checkbox.setChecked(list.get(position).isSelected());
HistoryRowModel rowModel = list.get(position);
Measure measure = rowModel.getMeasure();
long time = measure.getTimestamp();
DateFormat dateFormat = SimpleDateFormat.getDateInstance();
holder.text.setText(dateFormat.format(time));
int resource = getImage(measure.getThreshold());
if(resource == -1)
{
holder.imageView.setImageResource(R.drawable.unknown);
}
else
{
holder.imageView.setImageResource(resource);
}
return view;
}
}
And here is my remove from list code:
private void removeSelectedRows() {
View v;
CheckBox cb;
for (int i = 0; i < list.getCount(); i++) {
v = list.getAdapter().getView(i, null, null);
cb = (CheckBox) v.findViewById(R.id.history_list_check);
if(cb.isChecked())
{
removeMeasure(i);
}
}
}
private void removeMeasure(long rowId) {
Measure toRemove = adapter.getItem((int)rowId);
try {
Dao<Measure, Integer> measureDao = databaseHelper.getMeasureDao();
DeleteBuilder<Measure, Integer> db = measureDao.deleteBuilder();
db.where().eq("id", toRemove.getId());
measureDao.delete(db.prepare());
}
catch(Exception e) {
e.printStackTrace();
}
adapter.remove(toRemove);
}
My problem is that when I check some item and then invoke removeSelectedRows its remove always last item from list. Then when I return from this activity and go back again it's turn out that the proper row was delete from database and list show proper list rows. So it's looks like line
adapter.remove(toRemove);
remove wrong item from adapter. Any idea what is wrong with this code?
SOLVED
njzk2 was right in his comment

Replace all your adapter calls with list.getAdapter() calls. Or at least show us how you initialize the adapter variable.
EDIT: The notifyOnChange flag is 'true' by default so calling any of the following adapter methods will invoke the notifyDataSetChanged() method of the same object: add(T), insert(T), remove(T), clear()

Related

how to hide/show Imageview on Button Click for Custom Adapter Layout

I have custom adapter for ListView. The ListView is in activity_main.xml and I have a ImageView in CustomAdapter layout which is populated with ListView using CustomAdapter.
My Question is I have to hide/show that image which is in custom layout with a button present in main layout. Like if there is 10 row in my ListView and 10 row have that image. I want to hide only for the particular row.
I hope you understand my question...Thanks in Advance
Here's my ListViewAdapter
public class ListViewAdapter extends ArrayAdapter<FileName> {
Context context;
LayoutInflater inflater;
List<FileName> filenames;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context,int resource,List<FileName> filenames) {
super(context, resource, filenames);
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.filenames = filenames;
inflater = LayoutInflater.from(context);
}
private class ViewHolder {
TextView filename;
TextView shorttext;
ImageView imageView;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
return view;
}
}
name = filenames.get(position).getName(); //getting the positin from listview
filenames.set(name,FileName.isVisible = true); //getting error on isVisible
I have writen a Sample code and tested
MainActivity
public class MainActivity extends AppCompatActivity {
List<FileName> filenames;
DBhelper dBhelper;dBhelper
SQLiteDatabase sqLiteDatabase;
ListViewAdapter listViewAdapter;
ListView listView;
ImageView lock;
String name;
//temporary button i have added
Button lockBTN;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_sample);
Toolbar toolbar = (Toolbar) findViewById(R.id.toolbar);
setSupportActionBar(toolbar);
listView = (ListView) findViewById(R.id.lv_filename);
lockBTN = (Button) findViewById(R.id.lock);
filenames = getResult();
listViewAdapter = new ListViewAdapter(this, filenames);
listView.setAdapter(listViewAdapter);
lockBTN.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//giving statically position is 2
int position = 2;
// when you press menu button or any other button
FileName fileName = filenames.get(position);
//here you can set true-Show and false-hide imageview
fileName.setVisible(true);
//and update the list
filenames.set(position, fileName);
listViewAdapter.notifyDataSetChanged();
}
});
}
//temporary data to show on listview
private List<FileName> getResult() {
List<FileName> fileNames = new ArrayList<>();
String[] nameArr = {"Name1", "Name2", "Name3"};
String[] shortTextArr = {"ShortText1", "ShortText2", "ShortText3"};
for(int i=0; i<nameArr.length;i ++){
FileName fileName = new FileName();
fileName.setName(nameArr[i]);
fileName.setShorttext(shortTextArr[i]);
//setting default is hide to imageview
fileName.setVisible(false);
fileNames.add(fileName);
}
return fileNames;
}
}
FileName
public class FileName {
private String name;
private String shorttext;
private boolean visible = true;
public String getName() {
return name;
}
public void setName(String _name) {
this.name = _name;
}
public String getShorttext() {
return shorttext;
}
public void setShorttext(String _shorttext) {
this.shorttext = _shorttext;
}
public boolean isVisible() {
return visible;
}
public void setVisible(boolean visible) {
this.visible = visible;
}
}
ListViewAdapter
public class ListViewAdapter extends BaseAdapter{
Context context;
LayoutInflater inflater;
List<FileName> filenames;
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Context context, List<FileName> filenames) {
mSelectedItemsIds = new SparseBooleanArray();
this.context = context;
this.filenames = filenames;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
return filenames.size();
}
#Override
public Object getItem(int position) {
return filenames.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
//holder.filename.setPaintFlags(holder.filename.getPaintFlags() | Paint.STRIKE_THRU_TEXT_FLAG);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
// check weather image is to show/hide
if (filenames.get(position).isVisible()) {
holder.imageView.setVisibility(View.VISIBLE);
} else {
holder.imageView.setVisibility(View.GONE);
}
return view;
}
private class ViewHolder {
TextView filename;
TextView shorttext;
ImageView imageView;
}
}
activity_main.xml
<RelativeLayout 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"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="5dp"
android:orientation="vertical">
<ListView
android:id="#+id/lv_filename"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:layout_above="#+id/lock"/>
<Button
android:id="#+id/lock"
android:layout_alignParentBottom="true"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Lock"/>
</RelativeLayout>
custom_list_item.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
android:orientation="horizontal"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:weightSum="1">
<ImageView
android:id="#+id/imageView"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/utilities_notepad_icon" />
<LinearLayout
android:layout_width="232dp"
android:layout_height="match_parent"
android:orientation="vertical"
android:layout_weight="0.77">
<TextView
android:id="#+id/item_title"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:paddingBottom="1dp"
android:paddingTop="5dp"
android:text="Item Title"
android:textSize="16dp" />
<TextView
android:id="#+id/item_desc"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:maxLength="35"
android:paddingBottom="5dp"
android:paddingTop="1dp"
android:text="Item Description"
android:textColor="#999"
android:textSize="10dp" />
</LinearLayout>
<ImageView
android:id="#+id/lock"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="#drawable/lo"
android:layout_marginTop="13sp" />
</LinearLayout>
Take a extra variable in your FileName class.
public class FileName {
public String name;
public String shortText;
public boolean visible = true; // Set the default value to true.
}
Now on external button click in your main layout, you might consider updating the list item accordingly. Just set the visible variable to false of that item you want to hide. Then call notifyDataSetChanged() on your adapter to reload the data.
And yes, in your adapter, just check the value of visible attribute and then decide to hide/show the ImageView. So the getView function of your adapter should look like this.
public View getView(int position, View view, ViewGroup parent) {
final ViewHolder holder;
if (view == null) {
holder = new ViewHolder();
view = inflater.inflate(R.layout.listview_item, null);
// Locate the TextViews in listview_item.xml
holder.filename = (TextView) view.findViewById(R.id.item_title);
holder.shorttext = (TextView) view.findViewById(R.id.item_desc);
holder.imageView = (ImageView) view.findViewById(R.id.lock);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
// Capture position and set to the TextViews<br />
holder.filename.setText(filenames.get(position).getName());
holder.shorttext.setText(filenames.get(position).getShorttext());
// Hide/Show the ImageView
if (filenames.get(position).visible) holder.imageView.setVisibility(View.VISIBLE);
else holder.imageView.setVisibility(View.GONE);
return view;
}
I would suggest you to use RecyclerView instead of ListView. RecyclerView got more performance than the ListView. Now a days all are using RecyclerView instead of old ListView, it is quite easy to use as well.
And for handling your case create a function to remove the file name you wanted to remove in the RecyclerViewAdapter class as below
removeImageView(position){
fileNames.remove(position);
this.notifyItemRemoved(position);
}
notifyItemRemoved call will refresh the position in the recycler view and you will also get a nice view removing animation out of the box.

use Custome ListView with TextView And CheckBox With Single Selection of CheckBox

Hear i use Custom ListView with TextView and CheckBox.
But i want that Single Selection in CheckBox At a time
One CheckBox Selected then other one is Deselect
using BaseAdapter
but This code not Work Properly ..
Please Give me Suggestion ..thnks
#Override
public View getView(final int position, View view, ViewGroup parent) {
Integer selected_position = -1;
holder = new ViewHolder();
final Items itm = rowItem.get(position);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = layoutInflater.inflate(R.layout.activity_custom_list,
parent, false);
holder.tvItemName = (TextView) view.findViewById(R.id.textView1);
holder.check = (CheckBox) view.findViewById(R.id.checkBox1);
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
holder.tvItemName.setText(itm.getItems());
if (position == selected_position)
holder.check.setChecked(true);
else
holder.check.setChecked(false);
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if (holder.check.isChecked()) {
selected_position = position;
} else {
selected_position = -1;
}
notifyDataSetChanged();
}
});
return view;
}}
use Custom List-View with Text-View And Check-Box With Single Selection of Check Box
So many try then finally i got the Solution I hope it is Useful Code to you All...
This code Help you to create custom List-view with Text-view and Check-box then you select one check-box and if you select another one the first should automatically be Deselected.....Thank You...
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"
tools:context="com.example.listviewdemo2.MainActivity" >
<ListView
android:id="#+id/listView1"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:layout_alignParentLeft="true"
android:layout_alignParentTop="true" />
</RelativeLayout>
activity_custom_list.xml
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:tools="http://schemas.android.com/tools"
android:id="#+id/LinearLayout1"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:orientation="vertical"
tools:context="com.example.listviewdemo2.CustomListActivity" >
<LinearLayout
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:background="#android:color/darker_gray" >
<TextView
android:id="#+id/textView1"
android:layout_width="80dp"
android:layout_height="wrap_content"
android:layout_marginLeft="20dp"
android:layout_marginTop="4dp"
android:layout_weight="0.39"
android:textAppearance="?android:attr/textAppearanceMedium" />
<CheckBox
android:id="#+id/checkBox1"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_marginLeft="150dp"
android:layout_marginTop="4dp"/>
</LinearLayout> </LinearLayout>
String.xml
<string-array name="name">
<item>Laptop</item>
<item>Mobile</item>
<item>Desktop</item>
<item>TV</item>
<item>Pendrive</item>
<item>Router</item>
<item>Notebook</item>
<item>Tablet</item>
<item>I-pad</item>
<item>Bluetooth</item>
<item>HomeTheator</item>
</string-array>
MainActivity.java
String[] ItemName;
List<Items> rowItem;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
rowItem = new ArrayList<Items>();
ItemName = getResources().getStringArray(R.array.name);
for(int i = 0 ; i < ItemName.length ; i++)
{
Items itm = new Items(ItemName[i]);
rowItem.add(itm);
}
list = (ListView) findViewById(R.id.listView1);
CustomListActivity adapter = new CustomListActivity(this, rowItem);
list.setAdapter(adapter);
}
Items.java
public class Items {
private String items;
private boolean selected;
public Items(String items) {
this.items = items;
}
public String getItems() {
return items;
}
public void setItemName(String name) {
this.items = name;
}
public boolean getSelected() {
return selected;
}
public boolean setSelected(Boolean selected) {
return this.selected = selected;
}}
CustomListActivity.java
public class CustomListActivity extends BaseAdapter {
Context context;
List<Items> rowItem;
View listView;
boolean checkState[];
ViewHolder holder;
public CustomListActivity(Context context, List<Items> rowItem) {
this.context = context;
this.rowItem = rowItem;
checkState = new boolean[rowItem.size()];
}
#Override
public int getCount() {
return rowItem.size();
}
#Override
public Object getItem(int position) {
return rowItem.get(position);
}
#Override
public long getItemId(int position) {
return rowItem.indexOf(getItem(position));
}
public class ViewHolder {
TextView tvItemName;
CheckBox check;
}
#Override
public View getView(final int position, View view, ViewGroup parent) {
holder = new ViewHolder();
final Items itm = rowItem.get(position);
LayoutInflater layoutInflater = (LayoutInflater) context
.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (view == null) {
listView = new View(context);
listView = layoutInflater.inflate(R.layout.activity_custom_list,
parent, false);
holder.tvItemName = (TextView) listView
.findViewById(R.id.textView1);
holder.check = (CheckBox) listView.findViewById(R.id.checkBox1);
listView.setTag(holder);
} else {
listView = (View) view;
holder = (ViewHolder) listView.getTag();
}
holder.tvItemName.setText(itm.getItems());
holder.check.setChecked(checkState[position]);
holder.check.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
for(int i=0;i<checkState.length;i++)
{
if(i==position)
{
checkState[i]=true;
}
else
{
checkState[i]=false;
}
}
notifyDataSetChanged();
}
});
return listView;
}}
Show The Output :-
If you want a custom ListView with single choice CheckBox you can use something like this:
https://stackoverflow.com/a/12003125/5778152

how to code checkboxes created in custom listview

I've created a custom listView which lists all installed apps on the device, in this list is the app icon, app name and a checkbox. I want to code the onCheckboxClicked method but I don't know where to place it, I've read it should be within the adapter but other examples i've been looking at have code within the main activity and I can't seem to get it working either way.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
//retrieve currently installed apps
final Intent mainIntent = new Intent(Intent.ACTION_MAIN, null);
mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);
final List pkgAppsList = getPackageManager().queryIntentActivities( mainIntent, 0);
List<AppDetails> appList = new ArrayList<>();
for (Object object : pkgAppsList)
{
ResolveInfo info = (ResolveInfo) object;
Drawable icon = getBaseContext().getPackageManager().getApplicationIcon(info.activityInfo.applicationInfo);
String strAppName = info.activityInfo.applicationInfo.publicSourceDir.toString();
String strPackageName = info.activityInfo.applicationInfo.packageName.toString();
final String title = (String)((info != null) ? getBaseContext().getPackageManager().getApplicationLabel(info.activityInfo.applicationInfo) : "???");
AppDetails tmp = new AppDetails(title, icon);
appList.add(tmp); //add title and icon into list
}
final ListView listview = (ListView) findViewById(R.id.listView);
final AppDetailsAdapter adapter = new AppDetailsAdapter(this, appList);
listview.setAdapter(adapter);
}
adapter:
public class AppDetailsAdapter extends BaseAdapter {
private List<AppDetails> data;
private Context context;
public AppDetailsAdapter(Context context, List<AppDetails> data) {
this.context = context;
this.data = data;
}
#Override
public int getCount() {
return data.size();
}
#Override
public Object getItem(int position) {
return data.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
return view;
}
}
custom layout:
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="match_parent"
android:layout_height="60dp"
android:clickable="true"
android:orientation="horizontal"
android:weightSum="1">
<ImageView
android:id="#+id/icon"
android:layout_width="39dp"
android:layout_height="39dp"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp" />
<TextView
android:id="#+id/text"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_centerVertical="true"
android:layout_gravity="center_vertical"
android:layout_marginLeft="16dp"
android:textSize="17sp" />
<LinearLayout
android:orientation="horizontal"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:gravity="right" >
<CheckBox
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:id="#+id/checkBox"
android:onClick="onCheckboxClicked"/>/>
</LinearLayout>
I've also read that the getView method needs to be modified to handle the checkbox but again I can't seem to do it with what I've tried so far
Replace your adapter's get view code with below code :
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater vi = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = vi.inflate(R.layout.custom_row_layout, null);
}
ImageView icon = (ImageView) view.findViewById(R.id.icon);
TextView text = (TextView) view.findViewById(R.id.text);
CheckBox checkBox = (CheckBox) view.findViewById(R.id.checkBox);
final AppDetails item = data.get(position);
text.setText(item.name);
icon.setImageDrawable(item.icon);
checkBox .setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Handle your conditions here
}
});
return view;
}
here setOnCheckedChangeListener is method that you have to handle .

Custom List View with OnClickListener

I have custom ListView layout with a TextView and CheckBox. Everything works fine.
What I want is, when I click on the CheckBox or TextView (on the single View from ListView) both should behave like one object. (I can click on the CheckBox and it does not effect the TextView and TextView has no effect on CheckBox.) Code has no problem.
I have implemented all possible solutions but problem is still there. (One single click on every object of list should consider ONE COMPLETE CLICK for complete row.) I hope I explained very well.
MAIN ACTIVITY
package com.example.smsplanner;
public class SMSPlanner extends ListActivity {
ListView contactsListView;
private String TAG = "SMSPlanner"; CheckBox check;
int count;
List<ContactInfo> list = new ArrayList<ContactInfo>();
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
ph = new String[3];
phType = new String[3];
LoadContactListFromPhone();
ContactsAdapter contactadAdapter = new ContactsAdapter(this, list);
getListView().setChoiceMode(ListView.CHOICE_MODE_SINGLE);
setListAdapter(contactadAdapter);
}
#Override
public void onListItemClick(ListView parent, View v, int position, long id)
{
TextView tx =(TextView)v.findViewById(R.id.firstname);
TextView ph =(TextView)v.findViewById(R.id.phone);
Toast.makeText(this, tx.getText().toString() + " " + ph.getText().toString() + " " + Integer.toString(count), Toast.LENGTH_SHORT).show();
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
void LoadContactListFromPhone()
{
loadlistandreturns();
}
void call()
{
Toast toast = Toast.makeText(this, "Called...",Toast.LENGTH_LONG);
toast.show();
}
}
CUSTOM ADAPTER
public class ContactsAdapter extends ArrayAdapter<ContactInfo>
{
private final Activity context;
int resourceid;
List<ContactInfo> list = null;
public ContactsAdapter(Activity context, List<ContactInfo> list) {
super(context, R.layout.contactrow, list);
this.context = context;
this.list = list;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
final class ContactHolder{
TextView txtviewfirstname;
CheckBox chkselected;
TextView txtviewphone;
}
}
LAYOUT
<LinearLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:orientation="horizontal"
android:weightSum="100" >
<RadioGroup
android:id="#+id/rgStyle"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_weight="15"
android:orientation="vertical" >
<TextView
android:id="#+id/firstname"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceMedium" />
<TextView
android:id="#+id/phone"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:layout_marginLeft="5dp"
android:textAppearance="?android:attr/textAppearanceSmall" />
</RadioGroup>
<RadioGroup
android:id="#+id/rgStyle2"
android:layout_width="fill_parent"
android:layout_height="match_parent"
android:layout_weight="85"
android:orientation="vertical" >
<CheckBox
android:id="#+id/check"
android:layout_width="fill_parent"
android:layout_height="wrap_content"
android:checked="false"
android:focusable="false"
android:focusableInTouchMode="false" >
</CheckBox>
</RadioGroup>
</LinearLayout>
1. Bydefault all the Rows of the ListView are enabled to listen to click....
You must implement onItemClickListener() for the ListView....
See this example:
http://www.mkyong.com/android/android-listview-example/
you can use a CheckedTextView, or you can create a Checkable Layout, like this one :
http://tokudu.com/2010/android-checkable-linear-layout/
i think you should make adapter as
public class ContactsAdapter extends BaseAdapter {
ArrayList<ContactInfo> mlist;
Context mcontext;
public BluetoothChatadpter(Context context,ArrayList<ChatInfo> mchtlist) {
mlist = mchtlist;
mcontext = context;
}
#Override
public int getCount() {
return mlist.size();
}
#Override
public Object getItem(int postion) {
return mlist.get(postion);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(int position, View convertview, ViewGroup viewgroup){
View view = null;
if(convertview == null){
LayoutInflater inflater = context.getLayoutInflater();
view = inflater.inflate(R.layout.contactrow, null);
ContactHolder holder = new ContactHolder();
holder.txtviewfirstname = (TextView)view.findViewById(R.id.firstname);
holder.txtviewphone = (TextView)view.findViewById(R.id.phone);
holder.chkselected = (CheckBox)view.findViewById(R.id.check);
setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
// to open the selected file in resp
// do your work here
}});
chkselected .setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// Toast.makeText(context,// "checked is clicke="+pos, 12).show();
if (chkselected.isChecked())
{
// do your work here
} else {
// do your work here
}
}
});
view.setTag(holder);
}
else{
view = convertview;
}
ContactHolder holder2 = (ContactHolder) view.getTag();
holder2.txtviewfirstname.setText(list.get(position).firstname);
holder2.txtviewphone.setText(list.get(position).phonenumber);
holder2.chkselected.setChecked(list.get(position).selected);
return view;
}
}

how can i use list activity with controling my checked elements?

I googled and i tried to do this but couldnt implement successly.
My layout file
<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
android:orientation="vertical"
android:layout_width="fill_parent"
android:layout_height="fill_parent">
<ListView
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_weight="1"
android:id="#android:id/list"></ListView>
<Button
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:layout_gravity="center_horizontal"
android:text="buyButtonClickProduct"
android:id="#+id/buyButtonClickProduct"></Button>
</LinearLayout>
I have a custom adapter as :
private final List<Products> list;
private final Activity context;
public ProductsCustomAdapter(Activity context, List<Products> list) {
super(context, R.layout.coposite_product_info, list);
this.context = context;
this.list = list;
}
static class ViewHolder {
protected TextView productInfoText;
protected CheckBox checkbox;
protected ImageView imageOfProduct;
}
public View getView(int position, View convertView, ViewGroup parent) {
View view = null;
if (convertView == null) {
LayoutInflater inflator = context.getLayoutInflater();
view = inflator.inflate(R.layout.coposite_product_info, null);
final ViewHolder viewHolder = new ViewHolder();
viewHolder.imageOfProduct = (ImageView) view.findViewById(R.id.productImageView);
viewHolder.productInfoText = (TextView) view.findViewById(R.id.productInfoText);
viewHolder.checkbox = (CheckBox) view.findViewById(R.id.productCheck);
viewHolder.checkbox
.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
Products element = (Products) viewHolder.checkbox
.getTag();
element.setChecked(buttonView.isChecked());
}
});
view.setTag(viewHolder);
viewHolder.checkbox.setTag(list.get(position));
} else {
view = convertView;
((ViewHolder) view.getTag()).checkbox.setTag(list.get(position));
}
ViewHolder holder = (ViewHolder) view.getTag();
holder.productInfoText.setText(list.get(position).getInformation());
holder.imageOfProduct.setImageBitmap(list.get(position).getProductImage());
holder.checkbox.setChecked(list.get(position).isChecked());
return view;
}
I wanna get checked items from these but i couldn't reach them. When i debug it on my main class which is call listview.getCheckedItemPositions(); always turn for me "null"
This doesn't crash actually just always show "null" but i can see all my data in my listview.
SparseBooleanArray checkedItems = shopListView.getCheckedItemPositions();

Categories

Resources