Android: ListView elements with multiple clickable elements - android

I've a ListView where every element in the list contains a TextView and two different Buttons. Something like this:
ListView
--------------------
[ImageView][Text][CheckBox][Button]
--------------------
[ImageView][Text][CheckBox][Button]
--------------------
... (and so on) ...
With this code I can create an OnItemClickListener for the whole item:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> list, View view, int position, long id) {
Log.i(TAG, "onListItemClick: " + position);
}
}
});
However, I don't want the whole item to be clickable, but only the checkbox and the button of each list element.
So my question is, how do I implement a onClickListener for these two buttons with the following parameters:
int id (some id associated with each item in list)
int position (which is the element in the list on which the button click happened)

you need to make baseAdpter to achieve this
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;
}
}

i solved the same problem in this way:
in the layout.xml of the ListViewItem give the elements a tag, where you want to add the OnClickListener:
android:id="#+id/CheckBox"
android:tag="CheckBox" />
....
android:id="#+id/Button"
android:tag="Button" />
In the code, where your ListView is inflated add the OnClickListener with the following code:
listView.findViewWithTag("CheckBox").setOnClickListener(createCheckBoxOnClickListener(act));
listView.findViewWithTag("Button").setOnClickListener(createButtonOnClickListener(act));

You must do this in the getView method in your adapter..

easy, just implement the OnClickListener for these two buttons, and get the position that you get from getView(), make sure you set the position to final in order to get it in OnClickListener

you can add listeners in your getView() method of Adapter.

dont add onItemClickListener for the listview rather add onClick for your required button and for checkbox do it like this CheckBox cbox = new CheckBox(this);// find your checkbox from the view here.
cbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked){
// do what ever you want.
}
}
});

check below code it may help you.
private class ListViewAdapter extends BaseAdapter {
private LayoutInflater mInflater;
public ListViewAdapter(Context con) {
// TODO Auto-generated constructor stub
mInflater = LayoutInflater.from(con);
}
public int getCount() {
// TODO Auto-generated method stub
return main_genral_class.review_name.size();
}
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
ListContent holder;
if (convertView == null) {
convertView = mInflater.inflate(R.layout.review_row, null);
holder = new ListContent();
holder.img = (ImageView) convertView
.findViewById(R.id.imageView1);
holder.name = (TextView) convertView
.findViewById(R.id.textView1);
holder.check_date = (TextView) convertView
.findViewById(R.id.textView2);
holder.img.setOnClickListener(mOnTitleClickListener);
holder.name.setOnClickListener(mOnTitleClickListener1);
holder.check_date.setOnClickListener(mOnTitleClickListener2);
convertView.setTag(holder);
} else {
holder = (ListContent) convertView.getTag();
}
holder.text2.setText(main_genral_class.review_shout.get(position));
return convertView;
}
}
private OnClickListener mOnTitleClickListener = new OnClickListener() {
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v
.getParent());
Toast.makeText(review_activity.this, "click on Image View",
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mOnTitleClickListener1 = new OnClickListener() {
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v
.getParent());
Toast.makeText(review_activity.this, "click on Text View",
Toast.LENGTH_SHORT).show();
}
};
private OnClickListener mOnTitleClickListener2 = new OnClickListener() {
public void onClick(View v) {
final int position = mListView.getPositionForView((View) v
.getParent());
Toast.makeText(review_activity.this, "click on Date Text View",
Toast.LENGTH_SHORT).show();
}
};

Related

how to check the check box in ListView and change the text in same row in listView?

I have list view with check box and text view. When i checked check box, change the text in same row. This way i will check all the check boxes in list view and change the text in every row. Can any one explain with sample code?
public class DialogAdapter extends BaseAdapter{
//private LayoutInflater inflater = null;
ArrayList<String> timeList = new ArrayList<String>();
Context context;
public DialogAdapter(Context context, ArrayList<String> timeList) {
// TODO Auto-generated constructor stub
this.context = context;
this.timeList = timeList;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
//return timings.size();
return timeList.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return timeList.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#SuppressLint("ViewHolder")
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
//String timing = "10-30,14-08,16-30,19-00";
LayoutInflater inflater = (LayoutInflater)getSystemService(LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.dialog_row_list,null);
//timeListView.setVisibility(convertView.VISIBLE);
TextView txt_time=(TextView) convertView.findViewById(R.id.text_times);
txt_time.setText(timeList.get(position).toString());
EditText comments=(EditText)convertView.findViewById(R.id.editText_comment);
final TextView txt_Action=(TextView) convertView.findViewById(R.id.textView_act);
CheckBox cBox= (CheckBox) convertView.findViewById(R.id.checkBox_action);
cBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#SuppressLint("ResourceAsColor")
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
int getPosition = (Integer) buttonView.getTag();
timeList.get(getPosition).setSelected(buttonView.isChecked());
Toast.makeText(context, "position"+getPosition, 0).show();
if(isChecked){
txt_Action.setText("finished");
txt_Action.setTextColor(R.color.Green);
}
else{
txt_Action.setText("UnChecked");
txt_Action.setTextColor(R.color.Red);
}
}
});
return convertView;
}
}
this is my code please check n give solution how to change listview text when check checkbox in listview???
in the getView method of your ListView adapter:
if(yourCheckBox.isChecked)
yourTextView.setText("text if checkBox is checked.");
else
yourTextView.setText("text if checkBox is not checked.");
There is view before checkboxes and texviews that is listview ,if u want to access textviews from listview please make sure you are accessing from listview one item layout
Like
TextView txtvw=findViewByID(ur_layout_of_list_item).findViewByID(ur_textview);
after that changes will be done.
First I will suggest you to use ViewHolder pattern for listview adapter so that you don't need to do findViewById() everytime you scroll your list this will prevent your listview from performance slow down and also I would prefer to use setOnClickListener() over CheckedChangeListener().
Below is the sample code you can try
public class CustomAdapter extends BaseAdapter {
private Context context;
public static ArrayList<Item> modelArrayList;
public CustomAdapter(Context context, ArrayList<Item> modelArrayList){
this.context = context;
this.modelArrayList = modelArrayList;
}
#Override
public int getViewTypeCount() {
return getCount();
}
#Override
public int getItemViewType(int position) {
return position;
}
#Override
public int getCount() {
return modelArrayList.size();
}
#Override
public Object getItem(int position) {
return modelArrayList.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent){
ViewHolder viewHolder;
if (convertView == null) {
convertView = LayoutInflater.from(context).inflate(R.layout.layout_list_view_row_items, parent, false);
viewHolder = new ViewHolder(convertView);
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
Item currentItem = (Item) getItem(position);
if(currentItem.isChecked())
viewHolder.tvName.setText("Checked);
else
viewHolder.tvName.setText("Unchecked);
viewHolder.checkBox.setChecked(currentItem.isChecked());
viewHolder.checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
final boolean checked = currentItem.isChecked();
if(checked){
viewHolder.checkBox.setChecked(!checked);
viewHolder.tvName.setText("Unchecked");
currentItem.setChecked(!checked);
}else{
viewHolder.checkBox.setChecked(checked);
viewHolder.tvName.setText("Checked");
currentItem.setChecked(checked);
}
}
});
return convertView;
}
private class ViewHolder {
protected CheckBox checkBox;
private TextView tvName;
public ViewHolder(View view) {
checkBox = (CheckBox)view.findViewById(R.id.checkbox);
tvName = (TextView) view.findViewById(R.id.textView);
}
}
}

custom listview with only one checkbox is selected one at a time

I have a custom listview with each row contaning a checkbox and text. now what i want that if any one checkbox of listview row is checked so others checkbox in other row if checked .it will be delected automatically.(i.e only one checkbox should be selected one at a time).how should i do that.
So far what i have done is as follows:
public class CustomAdapter extends BaseAdapter{
Context context;
List<String> items;
boolean array[];
public CustomAdapter(Context context, List<String> items) {
super();
this.context = context;
this.items = items;
array =new boolean[items.size()];
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return items.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return items.get(position);
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertView;
final int pos=position;
if(v==null)
{
v=LayoutInflater.from(context).inflate(R.layout.list,null);
}
TextView txt1=(TextView) v.findViewById(R.id.textView1);
final CheckBox chkbox=(CheckBox) v.findViewById(R.id.checkBox1);
txt1.setText(items.get(position));
int selectedindexitem=0;
chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(chkbox.isChecked())
{
array[pos]=true;
}else{
array[pos]=false;
}
}
});
chkbox.setChecked(array[pos]);
return v;
}
}
In this code i can select multiple checkbox at a time but i need only one checkbox should be checked one at a time.
You need to keep track of selected item and code accordingly.
public class CustomAdapter extends BaseAdapter{
Integer selected_position = -1;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// Your Code
chkbox.setChecked(position==selected_position);
chkbox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked)
{
selected_position = position;
}
else{
selected_position = -1;
}
notifyDataSetChanged();
}
});
return convertView;
}
}
Try to change all item boolean value false exclude selected item after notify adapter and also implement ViewHolder design pattern for ListView performance :
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if(convertView==null){
holder = new ViewHolder();
convertView = LayoutInflater.from(context).inflate(R.layout.list,null);
holder.txt1 = (TextView) convertView.findViewById(R.id.textView1);
holder.chkbox = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
}else{
holder = (ViewHolder) convertView.getTag();
}
holder.txt1.setText(items.get(position));
holder.chkbox.setChecked(array[position]);
holder.chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
for (int i=0;i<array.length;i++){
if(i==position){
array[i]=true;
}else{
array[i]=false;
}
}
notifyDataSetChanged();
}
});
return convertView;
}
class ViewHolder{
TextView txt1;
CheckBox chkbox;
}
Maintain a variable:
int checked = -1; //say
Whenever you try to check a checkbox you check this variable, if it is -1 then check the checkbox and save the position of the list item in checked variable, when you try to check other checkbox again, if the variable ain't equal to -1 you first uncheck the checkbox at the position stored in checked variable, and then check the checkbox at current position and save the current position in checked variable
#Override
public View getView(int position, View convertView, ViewGroup parent) {
// TODO Auto-generated method stub
View v=convertView;
final int pos=position;
if(v==null)
{
v=LayoutInflater.from(context).inflate(R.layout.list,null);
}
TextView txt1=(TextView) v.findViewById(R.id.textView1);
final CheckBox chkbox=(CheckBox) v.findViewById(R.id.checkBox1);
txt1.setText(items.get(position));
int selectedindexitem=0;
if(position==selected_position)
{
chkbox.setChecked(true);
}
else
{
chkbox.setChecked(false);
}
chkbox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(chkbox.isChecked())
{
array[pos]=true;
selected_position = pos;
}else{
array[pos]=false;
}
}
});
chkbox.setChecked(array[pos]);
MainActivity.lv.setAdapter(new CustomAdapter(context,MainActivity.listitems));
return v;
}
Easy to maintain your selection. Get your selection from the model.
class PropertyModel{
String VAL= "SOME VALUE"
boolean selected = false;
public String getVAL() {return VAL;}
public void setVAL(String VAL) {this.VAL = VAL;}
public boolean isSelected() {return selected;}
public void setSelected(boolean selected) {this.selected = selected;}
}
Prepare your view like this:
public class CheckBoxAdptr extends BaseAdapter{
/*
..........
*/
public View getView(int position, View view, ViewGroup parent) {
PropertyModel items = list.get(position);
View row;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.list_item_checkbox, null);
}
else{row = view;}
TextView T1 = (TextView) row.findViewById(R.id.list_item_1);
CheckBox checkBox = (CheckBox) row.findViewById(R.id.list_item_check_box);
T1.setText(""+items.getVAL());
if(items.isSelected()){
checkBox.setChecked(true);
}
else {checkBox.setChecked(false);}
return row;
}
}
Now in your activity or fragment set the adapter and do something like this:
final ArrayList<PropertyModel> list = getList();
CheckBoxAdptr adpt = new CheckBoxAdptr(getActivity(), list);
listview.setAdapter(adpt);
listview.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> adapterView, View view, int position, long id) {
for(int i = 0; i<list.size(); i++){
if(i!=position){
list.get(i).setSelected(false);
}
else{
list.get(i).setSelected(true);
}
}
adpt.notifyDataSetChanged();
}
});
Notice that all your work is done by adpt.notifyDataSetChanged() . Hope this helps.
Working with getView (like most of the answers posted) was not working properly for me. It was not responsive enough. Sometimes it would uncheck the previous checkbox, sometimes not.
This worked perfectly for me:
First we need to store the position of all previously checked checkboxes:
Set<Integer> selectedPreviousPositions = new HashSet<>();
Then in the onItemClick listener we uncheck all checkboxes before checking the one we selected.
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
boolean isChecked = ((CheckBox) view.findViewById(R.id.cbSelected)).isChecked();
if (!isChecked) {
final ListView listDevices = (ListView) findViewById(R.id.lvDevices);
for (Integer pos : selectedPreviousPositions ) {
View pView = listDevices.getChildAt(pos);
if (pView != null) { // unnecessary but we never know !
((CheckBox)pView.findViewById(R.id.checkboxID)).setChecked(false);
}
}
selectedUniquePositions.add(new Integer(position));
// Now we can check the selected checkbox
((CheckBox) view.findViewById(R.id.cbSelected)).setChecked(true);
} else {
((CheckBox) view.findViewById(R.id.cbSelected)).setChecked(false);
selectedPreviousPositions.remove(new Integer(position));
}
}
Inside the adapter, set OnClickListener() for checkBox. Whenever checkBox is clicked, store clicked checkBox position and call notifyDataSetChanged(). This will getView() method again for all views in your listview. Whenever, getView() called, you check the checkBox of previously stored postition and uncheck remaining checkboxes.
public class CustomAdapter extends ArrayAdapter<YourModelObject>
{
private int selectedCheckBoxPosition = -1;
public int getSelectedCheckBoxPosition()
{
return selectedCheckBoxPosition;
}
#Override
public View getView(final int position, View convertView, final ViewGroup parent)
{
final ViewHolder viewHolder;
LayoutInflater layoutInflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null)
{
convertView = layoutInflater.inflate(R.layout.list_item, null);
viewHolder = new ViewHolder();
viewHolder.checkBox = (CheckBox) convertView;
convertView.setTag(viewHolder);
}
else
{
viewHolder = (ViewHolder) convertView.getTag();
}
if (position == selectedCheckBoxPosition)
{
viewHolder.checkBox.setChecked(true);
Log.d(TAG, "checkbox CHECKED at pos: " + position);
}
else
{
viewHolder.checkBox.setChecked(false);
Log.d(TAG, "checkbox UNCHECKED at pos: " + position);
}
//viewHolder.checkBox.setText("sample text");
viewHolder.checkBox.setOnClickListener(new View.OnClickListener()
{
#Override
public void onClick(View view) {
selectedCheckBoxPosition = position;
Log.d(TAG, "onClick() - set selectedCheckBoxPosition = " + position);
notifyDataSetChanged();
}
});
return convertView;
}
private class ViewHolder
{
CheckBox checkBox;
}
}

click listener + checkbox - on android

public class ChooseFavorites extends Activity implements OnItemClickListener
{
StationManager st;
MyCustomAdapter arr;
ListView list;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_choose_favorites);
st = new StationManager();
list = (ListView)findViewById(R.id.stationsList1);
arr = new MyCustomAdapter(this, android.R.layout.simple_list_item_multiple_choice, st.getNamesOfStations());
list.setAdapter(arr);
list.setOnItemClickListener(this);
}
class MyCustomAdapter extends ArrayAdapter<String> implements OnClickListener
{
LayoutInflater inflater;
Context ctx;
CheckBox cb;
String[] stationNames;
TextView stationName1;
public MyCustomAdapter(Context context, int textViewResourceId, String[] stationNames) {
super(context, textViewResourceId, textViewResourceId, stationNames);
ctx = context;
this.stationNames = stationNames;
inflater = LayoutInflater.from(context);
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 23;
}
#Override
public String getItem(int position) {
// TODO Auto-generated method stub
return stationNames[position];
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row = convertView;
if(row==null)
{ // Object reuse
inflater = getLayoutInflater();
row = inflater.inflate(R.layout.favorite_row, parent, false);
}
stationName1 = (TextView)row.findViewById(R.id.textFavoriteItemInRow);
stationName1.setText(stationNames[position]);
cb=(CheckBox)row.findViewById(R.id.cbCheck);
row.setOnClickListener(this);
return row;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
toast.show();
}
}
#Override
public void onItemClick(AdapterView<?> arg0, View v, int position, long arg3) {
// TODO Auto-generated method stub
Toast toast = Toast.makeText(getApplicationContext(), "" + position, Toast.LENGTH_SHORT);
toast.show();
}
}
I don't know if you can see this only through code...
but If there were not an onClick in the class my costume adapter, nothing would have happen...
the android don't use the "on item click listener"
but it does work on the "on click" method....
the problem is : I DONT HAVE POSITION which I truly need...
hope anyone can help me about that! thank you all!
You can use this event to get notified about the checkbox being checked/unchecked
cb.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
}
}
Use Checkbox setOnCheckedChangeListener event.
Try like this...
CheckBox ChkBx = ( CheckBox ) findViewById( R.id.checkbox);
ChkBx.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
You can use following:
listView.setOnItemClickListener(new OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view,
int position, long id) {
Toast.makeText(getApplicationContext(),
"Click ListItem Number " + position, Toast.LENGTH_LONG)
.show();
}
});
Or u can save position as tag to checkbox and check on checkbox clicklistener
#Override
public View getView(int position, View convertView, ViewGroup parent)
{
// ur code...
**cb.setTag(position);**
row.setOnClickListener(this);
return row;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
**int position = v.getTag();** //cast & check for Tag not null too.
Toast toast = Toast.makeText(getApplicationContext(), "", Toast.LENGTH_SHORT);
toast.show();
}
#Override
public View getView(final int position, View convertView, ViewGroup parent)
{
// TODO Auto-generated method stub
View row = convertView;
if(row==null)
{ // Object reuse
inflater = getLayoutInflater();
row = inflater.inflate(R.layout.favorite_row, parent, false);
}
stationName1 = (TextView)row.findViewById(R.id.textFavoriteItemInRow);
stationName1.setText(stationNames[position]);
cb=(CheckBox)row.findViewById(R.id.cbCheck);
cb.setOnCheckedChangeListener(new CompoundButton.
OnCheckedChangeListener(){
#Override
public void onCheckedChanged(CompoundButton buttonView,boolean isChecked) {
if (isChecked)
{
cb.setChecked(isChecked);
Toast toast = Toast.makeText(getApplicationContext(), "checked" + position, Toast.LENGTH_SHORT);
toast.show();
}
else
{
cb.setChecked(isChecked);
Toast toast = Toast.makeText(getApplicationContext(), "unChecked" + position, Toast.LENGTH_SHORT);
toast.show();
}
}
});
return row;
}
}
public View getView(int position, View convertView, ViewGroup parent) {
viewHolder holder;
// Reuse an existing view, if one is supplied, otherwise create a new one
// Check to see if this one is created yet ?
if (convertView == null){
// Get inflater
LayoutInflater inflater = (LayoutInflater)
parentActivity.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
// Create a view for it
convertView = inflater.inflate(R.layout.test_reprot_lv_items, parent, false);
// Creates a holder class to contain all objects of a row
holder = new viewHolder();
holder.equipmentID = (TextView) convertView.findViewById(R.id.equipmentID);
holder.checkBox = (CheckBox) convertView.findViewById(R.id.checkBox);
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set checkBox's Tag with the position of the row in the listview
holder.checkBox.setTag(position);
// Sets the tag associated with this view for later reuse.
convertView.setTag(holder);
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
holder.checkBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int location = (Integer) c.getTag();
// Set selected state with the location of the row in the listview
itemsList.get(location).setSelectedState(c.isChecked());
}
});
}
else{
// In order to reuse the preallocated memory, get the holder from View's tag,
// which is allocated and saved in this view object. When a view requests
// to be rendered and it has not been instantiated, we new a holder and save
// it to View's 'Tag' for later reuse.
holder = (viewHolder) convertView.getTag();
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set checkBox's Tag with the position of the row in the listview
holder.checkBox.setTag(position);
holder.checkBox.setOnClickListener(new OnClickListener(){
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
int location = (Integer) c.getTag();
//++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set selected state with the location of the row in the listview
// The method setSelectedState, which provided by your own class,
// is called to update the checkbox state.
itemsList.get(location).setSelectedState(c.isChecked());
}
});
}
//+++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++++
// Set checkbox state with calling the method getSelectedState which
// provied by your own class.
holder.checkBox.setChecked(itemsList.get(position).getSelectedState());
return convertView;
}

Given a listview with many data fields per row, how to separate only one field (id) from the row with onClickListener()

Given a listview with many data fields per row, how can we separate only one field (say an id) from the row withonClickListener()
public void onItemClick(AdapterView<?> arg0, View arg1, int position, long arg3) {
Object dataRow = listView.getItemAtPosition(position);
Log.e("hi, this is the full row of data, i just want 1 of the fields", dataRow);
}
This can be achieved by custom listview by extending BaseAdapter to a class.. In the class you can
Inside oncreate :
listview.setAdapter(new newListview(this); //listview is the object of ListView in xml file
outside onCreate and newListview is the innerclass for the activity
class newListview extends BaseAdapter{
private Context context;
public PrayerList(Context context) {
this.context=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return 0;// here return size of listview
}
#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(final int position, View view, ViewGroup viewgroup) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(context);
if (view == null)
{
view = inflater.inflate(R.layout.mydatalistview, null);
holder = new ViewHolder();
holder.txtViewTitle = (TextView) view.findViewById(R.id.title);
holder.txtViewDescription = (TextView) view.findViewById(R.id.description);
holder.arrowImage=(ImageView)view.findViewById(R.id.arrow_imageview);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
//here you can use onclick of particular item of listview
}
}
class ViewHolder{
TextView txtViewTitle;
TextView txtViewDescription;
ImageView arrowImage;
}

Imageview in Listview cannot change at runtime in android

I am developing Android Application. In which i am having list view with text and image. i need to set the imageview visible at run time. ie. when i clicked the view it should appear and when i click next view previous view have to disappear and corresponding imageview in clicking view have to appear.
Now i am success in displaying text but i am strucking in appearance of imageview. Inside the onclick of item list i cannot set the resource for imageview
Below is my code.
public class ListofCategory extends Activity{
ListView listview;
List<String> mycategoryId,mycategoryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.listofcategory);
listview=(ListView)findViewById(R.id.category_listview);
mycategoryId=new ArrayList<String>();
mycategoryName=new ArrayList<String>();
getData();
listview.setAdapter(new MyListAdapter(this));
//setListAdapter(new MyListAdapter(this));
}
class MyListAdapter extends BaseAdapter{
private Context context;
MyListAdapter(Context context)
{
this.context=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mycategoryId.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(context);
if (view == null)
{
view = inflater.inflate(R.layout.mycategorylist, null);
holder = new ViewHolder();
holder.categoryname = (TextView) view.findViewById(R.id.title);
holder.categorycount = (TextView) view.findViewById(R.id.description);
holder.arrow=(ImageView)view.findViewById(R.id.arrow_imageview);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
holder.categoryname.setText(mycategoryName.get(position));
holder.categoryname.setTextSize(18.0f);
//holder.arrow.setImageResource(R.drawable.arrow);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Problem occurs here.. This holder value ask me to change as final but here i cannot make holder to final
holder.arrow.setImageResource(R.drawable.arrow);
//finish();
}
});
return view;
}
}
class ViewHolder
{
TextView categoryname;
TextView categorycount;
ImageView arrow;
}
}
Please anyone give me a better solution..its very urgent.. Thanks in advance
Create a final pointer for the imageView.
final ImageView tempView = holder.arrow;
than in the onclick:
tempView.setImageResource(R.drawable.arrow);
Added to the class a field:
MyListAdapter myAdapter;
In the oncreate method do this:
myAdapter = new MyListAdapter(this);
listview.setAdapter(myAdapter);
On the onclick event do this:
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
Problem occurs here.. This holder value ask me to change as final but here i cannot make holder to final
tempView.setImageResource(R.drawable.arrow);
myAdapter.notifyDataSetChange();
}
});
That should work.
Try this:
ViewHolder tmpHolder = null;
if( view == null ) {
.
.
.
tmpHolder = new ViewHolder();
} else {
tmpHolder = (ViewHolder) view.getTag();
}
final ViewHolder holder = tmpHolder;
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
holder.arrow.setImageResource(R.drawable.arrow);
//finish();
}
});
As far as I can understand,
I think instead of using view onClickListener use, the layout onClickListener which is used in R.layout.mycategorylist.
Or else, you can use holder.categoryname onClickListener or holder.categorycount listeners right.
and You can declare ViewHolder holder ; as global variable in your MyListAdapter right, then there is no issue for declaring final or something.
Hope it helps
public void onItemClick(AdapterView<?> arg0, View view, int position,
long id) {
// TODO Auto-generated method stub
ImageView image;
RelativeLayout layout = (RelativeLayout) view;//Layout of mycategorylist
image = (ImageView) layout.getChildAt(0);//image is added first here.change accordingly
image.setImageDrawable(....imageId);
}
public class ListofCategory extends Activity{
ListView listview;
List<String> mycategoryId,mycategoryName;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
requestWindowFeature(Window.FEATURE_NO_TITLE);
getWindow().setFlags(WindowManager.LayoutParams.FLAG_FULLSCREEN,
WindowManager.LayoutParams.FLAG_FULLSCREEN);
setContentView(R.layout.listofcategory);
listview=(ListView)findViewById(R.id.category_listview);
mycategoryId=new ArrayList<String>();
mycategoryName=new ArrayList<String>();
getData();
listview.setAdapter(new MyListAdapter(this));
//setListAdapter(new MyListAdapter(this));
}
class MyListAdapter extends BaseAdapter{
private Context context;
private ImageView previous;
MyListAdapter(Context context)
{
this.context=context;
}
#Override
public int getCount() {
// TODO Auto-generated method stub
return mycategoryId.size();
}
#Override
public Object getItem(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public long getItemId(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(final int position, View view, ViewGroup viewgroup) {
ViewHolder holder = null;
LayoutInflater inflater = LayoutInflater.from(context);
if (view == null)
{
view = inflater.inflate(R.layout.mycategorylist, null);
holder = new ViewHolder();
holder.categoryname = (TextView) view.findViewById(R.id.title);
holder.categorycount = (TextView) view.findViewById(R.id.description);
holder.arrow=(ImageView)view.findViewById(R.id.arrow_imageview);
view.setTag(holder);
}
else
{
holder = (ViewHolder) view.getTag();
}
holder.categoryname.setText(mycategoryName.get(position));
holder.categoryname.setTextSize(18.0f);
//holder.arrow.setImageResource(R.drawable.arrow);
view.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v)
{
if(previous!=null){
previous.setVisibility(View.Invisible);
v.setVisibility(View.Visible);
previous = v;
}
}
});
return view;
}
}
class ViewHolder
{
TextView categoryname;
TextView categorycount;
ImageView arrow;
}

Categories

Resources