Multiple checkboxes get (de)selected when one is checked in Gridview - Android - android

So I have a Gridview where each grid item consists of an ImageView and a Checkbox. It calls Image Adapter to populate the grid dynamically. Now, when I select one checkbox, lets say number 5, another checkbox like number 12 gets selected automatically. Similar for deselection. I cannot figure out why this is happening. Any help will be appreciated. Thanks!
public class SignupFarmerCrop extends ActionBarActivity implements View.OnClickListener {
GridView gridView;
private ImageAdapter adpt;
private List<DistrictCommodity> localResponse;
private MediaPlayer mp;
private boolean[] thumbnailsselection;
private int count;
private PreferencesHelper oldSignup;
private String district;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_signup_farmer_crop);
setVolumeControlStream(AudioManager.STREAM_MUSIC);
ImageButton sound = (ImageButton) findViewById(R.id.button);
sound.setOnClickListener(this);
oldSignup = new PreferencesHelper(this);
district = oldSignup.getStringPreferences("districtId");
String language = Locale.getDefault().getLanguage();
if (language.equals("en"))
language = "L001";
else
language = "L002";
// Exec async load task
new EndpointsDistrictCropAsyncTask().execute(new Pair<Context, String>(this, district),
new Pair<Context, String>(this, language));
gridView = (GridView) findViewById(R.id.gridView1);
adpt = new ImageAdapter(this, localResponse);
gridView.setAdapter(adpt);
public void onClick(View v) {
if (mp != null) mp.release();
mp = MediaPlayer.create(this, R.raw.fname);
mp.start();
}
/** Called when the user clicks a crop button */
public void goConfirm(View view) {
// Do something in response to button
Intent intent = new Intent(this, SignupConfirmActivity.class);
startActivity(intent);
}
#Override
protected void onDestroy() {
if(null!=mp){
mp.release();
}
super.onDestroy();
}
#Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
// Inflate the menu items for use in the action bar
MenuInflater inflater = getMenuInflater();
inflater.inflate(R.menu.menu_signup_farmer_crop, menu);
return super.onCreateOptionsMenu(menu);
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
return super.onOptionsItemSelected(item);
}
public class ImageAdapter extends BaseAdapter {
private Context context;
private List<DistrictCommodity> crops;
private final Logger logger = Logger.getLogger(ImageAdapter.class.getName());
public ImageAdapter(Context context, List<DistrictCommodity> activeResponses) {
this.context = context;
this.crops = activeResponses;
}
public View getView(int position, View convertView, ViewGroup parent) {
View gridView = convertView;
ViewHolder holder;
if (gridView == null) {
holder = new ViewHolder();
LayoutInflater inflater = (LayoutInflater) context
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
gridView = inflater.inflate(R.layout.activity_signup_crop_grid, null);
holder.checkbox = (CheckBox) gridView.findViewById(R.id.grid_item_label);
holder.imageview = (ImageView) gridView.findViewById(R.id.grid_item_image);
gridView.setTag(holder);
}
else {
holder = (ViewHolder) gridView.getTag();
}
holder.checkbox.setId(position);
holder.imageview.setId(position);
holder.checkbox.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
CheckBox cb = (CheckBox) v;
int id = cb.getId();
logger.warning("Id of checkbox is: " + id);
if (thumbnailsselection[id]) {
cb.setChecked(false);
thumbnailsselection[id] = false;
} else {
cb.setChecked(true);
thumbnailsselection[id] = true;
}
}
});
holder.checkbox.setText(crops.get(position).getCommodity());
String crop = crops.get(position).getType();
logger.warning("Image file called is #drawable/" + crop + ".png and context is: " + context.getPackageName());
Drawable drawable = context.getResources().getDrawable(context.getResources()
.getIdentifier("#drawable/potato", null, context.getPackageName()));
holder.imageview.setImageDrawable(drawable);
holder.id = position;
return gridView;
}
#Override
public int getCount() {
return count;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
public void setActiveDeals(List<DistrictCommodity> activeResponses) {
this.crops = activeResponses;
}
}
class ViewHolder {
ImageView imageview;
CheckBox checkbox;
int id;
}
}

MainActivity.java
private void enterEditMode() {
try {
listView.setAdapter(null);
listView.setOnItemClickListener(null);
db = new MySQLiteHelper(this);
//call the note object which hold all note object
List<note> note = db.getAllNotes();
int total = note.size();
//declare the values with specific number
String[] values = new String[total];
//add all the note innto the values
int counter = 0;
for (note note1 : note) {
values[counter] = note1.getSubject();
counter++;
}
db.close();
cbAdapter = new checkboxListviewAdapter(this,values);
// Assign adapter to ListView
listView.setAdapter(cbAdapter);
cbAdapter.notifyDataSetChanged();
} catch (Exception e) {
//tell user to send report
showMessage("Error!");
}
}
checkboxListviewAdapter.java
public class checkboxListviewAdapter extends BaseAdapter{
Context context;
String[] subjectList;
Boolean[] selectedList;
private LayoutInflater inflater;
public checkboxListviewAdapter (Context context, String[] subjectList ) {
this.context = context;
this.subjectList = subjectList;
selectedList = new Boolean[subjectList.length];
inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < selectedList.length; i++){
selectedList[i] = false;
}
}
#Override
public int getCount() {
return subjectList.length;
}
#Override
public Object getItem(int position) {
return subjectList[position];
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
Holder holder = null;
if (convertView == null) {
holder = new Holder();
convertView = inflater.inflate(R.layout.checkbox_listview_text_black, null);
holder.tv = (TextView) convertView.findViewById(R.id.textview1);
holder.cb = (CheckBox) convertView.findViewById(R.id.checkBox1);
convertView.setTag(holder);
} else {
holder = (Holder) convertView.getTag();
}
holder.cb.setChecked(selectedList[position]);
holder.tv.setText(subjectList[position]);
holder.cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedList[position] == false) {
selectedList[position] = true;
} else {
selectedList[position] = false;
}
}
});
return convertView;
}
static class Holder {
TextView tv;
CheckBox cb;
}
}
Explaination:
In checkboxListviewAdapter.java
1) Let's say you have 10 checkbox in your listview. So, create a boolean[] to hold your all checkbox's boolean value.
private boolean[] booleanList = new boolean[10];
2) In your constructor, use for loop to set booleanList's as false.
public checkboxListviewAdapter (Context context, String[] subjectList ) {
//this.context = context;
//this.subjectList = subjectList;
//selectedList = new Boolean[subjectList.length];
//inflater = (LayoutInflater) context.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
for (int i = 0; i < selectedList.length; i++){
selectedList[i] = false;
}
}
3) Now, in your getView, add the below code to get the boolean value from the booleanList and set the boolean value each time we scroll the listview.
holder.cb.setChecked(selectedList[position]);
4) Finally, to add a listener to your checkbox, use OnClickListener.
holder.cb.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if(selectedList[position] == false) {
selectedList[position] = true;
} else {
selectedList[position] = false;
}
}
});
5) run the code and check the result.

You are saving the state of the checkbox in thumbnailsselection when it's clicked, but you don't use that state in getView() to set up the initial appearance of the checkbox. So you are probably getting random checkbox states from recycled views.
Call holder.checkbox.setState() with the state from thumbnailsselection to create the GridView item with the correct checkbox appearance.

Related

android:how to use viewflipper in listview to animate one row at a time

I have a listview with a custom adapter.Each row of the listview contains two textviews and a viewflipper.
When I click a button, I want to animate/flip each row with a random text.
For animation, I used view flipper,but the animation is not working one after the other , rather it works simultaneously for all the rows.
My button click code is as follows.
public void onButtonClick(View view) {
customAdapter.setFlipRow(!(customAdapter.isFlipRow()));
listView.invalidateViews();
}
The custom adapter:
public class CustomAdapter extends BaseAdapter {
Context context;
String countryList[];
boolean flag[]= null;
int flags[];
LayoutInflater inflter;
Random r = null;
private static String TAG = "CustomAdapter";
public ViewHolder getViewHolder() {
return viewHolder;
}
ViewHolder viewHolder;
public boolean isFlipRow() {
return flipRow;
}
public void setFlipRow(boolean flipRow) {
this.flipRow = flipRow;
}
private boolean flipRow = false;
public CustomAdapter(Context applicationContext, String[] countryList) {
this.context = context;
this.countryList = countryList;
flag = new boolean[countryList.length];
for(int f = 0;f<flag.length;f++)
{
flag[f] = false;
}
inflter = (LayoutInflater.from(applicationContext));
r = new Random(5);
}
private static class ViewHolder {
TextView country;
TextView country1;
ViewFlipper viewFlipper;
ListView lv;
}
#Override
public View getView(int pos, View view, ViewGroup viewGroup) {
View v = view;
if(view == null)
{
viewHolder = new ViewHolder();
view = inflter.inflate(R.layout.listadapter, null);
viewHolder.country = (TextView) view.findViewById(R.id.textView);
viewHolder.country1 = (TextView) view.findViewById(R.id.bottomtextView);
viewHolder.viewFlipper = (ViewFlipper) view.findViewById(R.id.flipper);
viewHolder.lv = (ListView)view.findViewById(R.id.listView);
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.country.setText(countryList[pos]);
int rInt = r.nextInt(5);
if(isFlipRow()){
viewHolder.country1.setText("Random No: "+rInt);
viewHolder.viewFlipper.setFlipInterval(1000);
if(pos <= countryList.length-1)
{
flag[pos] = true;
if(pos == 0 && flag[pos]){
viewHolder.viewFlipper.startFlipping();
}
if(pos != 0 && flag[pos-1] == true){
viewHolder.viewFlipper.startFlipping();
flag[pos-1] = false;
/*viewHolder.viewFlipper.stopFlipping();
I tried to have a boolean flag for each row,
setting it before startFlipping() and resetting it after
stopFlipping().But adding this stopFlipping() here
stops all rows except first row and all rows flip at the
same time.Moreover getView is called only during setAdapter()
and invalidateviews().*/
}
if(pos == countryList.length-1){
Arrays.fill(flag,false);
}
}
}
else{
viewHolder.viewFlipper.stopFlipping();
Arrays.fill(flag,false);
}
return view;
}
}
All I need is to animate each row one at a time.But now all the rows are animating at the same time.Any insights or inputs will be really helpful.
Try this:
public void onButtonClick(View view) {
customAdapter.flipRow(view);
}
and adapter:
public class CustomAdapter extends BaseAdapter {
Context context;
String countryList[];
int rnds[];
LayoutInflater inflater;
Random r;
private boolean flipRow = false;
private int flipRowNum = 0;
Button btn;
final private static String TAG = "CustomAdapter";
final private static int FLIP_DELAY = 1000;
final private static int FLIP_COUNT = 2;
public boolean isFlipRow() {
return flipRow;
}
public void flipRow(View view) {
btn = (Button)view;
btn.setEnabled(false);
flipRow = true;
notifyDataSetChanged();
}
public CustomAdapter(Context context, String[] countryList) {
this.context = context;
this.countryList = countryList;
inflater = (LayoutInflater.from(context));
r = new Random(5);
rnds = new int[countryList.length];
for(int f = 0;f<rnds.length; f++)
{
rnds[f] = r.nextInt(5);
}
}
private class ViewHolder {
TextView country;
TextView country1;
ViewFlipper viewFlipper;
ListView lv;
}
#Override
public int getCount() {
return countryList.length;
}
#Override
public String getItem(int i) {
return countryList[i];
}
#Override
public long getItemId(int i) {
return i;
}
#Override
public View getView(int pos, View view, ViewGroup viewGroup) {
final ViewHolder viewHolder;
if(view == null)
{
viewHolder = new ViewHolder();
view = inflater.inflate(R.layout.listadapter, null);
viewHolder.country = (TextView) view.findViewById(R.id.textView);
viewHolder.country1 = (TextView) view.findViewById(R.id.bottomtextView);
viewHolder.viewFlipper = (ViewFlipper) view.findViewById(R.id.flipper);
//viewHolder.lv = (ListView)view.findViewById(R.id.listView);
view.setTag(viewHolder);
}else {
viewHolder = (ViewHolder) view.getTag();
}
viewHolder.country.setText(countryList[pos]);
viewHolder.country1.setText("Random No: " + rnds[pos]);
viewHolder.viewFlipper.setFlipInterval(0);
if(isFlipRow() && (pos == flipRowNum)){
viewHolder.viewFlipper.startFlipping();
viewHolder.viewFlipper.setFlipInterval(FLIP_DELAY);
viewHolder.viewFlipper.postDelayed(new Runnable() { //Stop flipping
#Override
public void run() {
viewHolder.viewFlipper.stopFlipping();
flipRow = !flipRow;
flipRowNum++;
if(flipRowNum == countryList.length) flipRowNum = 0;
btn.setEnabled(true);
}
}, (2*FLIP_COUNT - 1)*FLIP_DELAY + 50);
}
return view;
}
}
Hope that helps!

android share option for listview items

I want to share the listview items.Listview contains many items.But when i select third or any item other than the first item for sharing, it is taking only the first item for sharing.I have attached my code.Please help me to solve this.
public boolean onActionItemClicked(ActionMode mode, MenuItem item) {
switch (item.getItemId()) {
case R.id.share:
SparseBooleanArray selectedshare = adapter.getSelectedIds();
for (int i = (selectedshare.size() - 1); i >= 0; i--) {
if (selectedshare.valueAt(i)) {
val = list.get(i).getId();
System.out.println("idddddddddd"+val);
date = list.get(i).getDate();
System.out.println("dateeee"+date);
title = list.get(i).getTitle();
System.out.println("titleeee"+title);
content = list.get(i).getContent();
System.out.println("contenttttt"+content);
shareIt();
}
}
return true;
///////for sharing///////
default:
return false;
}
}
////here is the function//////
private void shareIt() {
//sharing implementation here
Intent sharingIntent = new Intent(android.content.Intent.ACTION_SEND);
sharingIntent.setType("text/plain");
sharingIntent.putExtra(android.content.Intent.EXTRA_SUBJECT, "All memories");
sharingIntent.putExtra(android.content.Intent.EXTRA_TEXT, "Date :"+date +"\n"+"Title :"+title+"\n"+"Content :"+ content);
startActivity(Intent.createChooser(sharingIntent, "Share via"));
}
#Override
public boolean onOptionsItemSelected(MenuItem item) {
// Handle action bar item clicks here. The action bar will
// automatically handle clicks on the Home/Up button, so long
// as you specify a parent activity in AndroidManifest.xml.
int id = item.getItemId();
//noinspection SimplifiableIfStatement
if (id == R.id.action_settings) {
return true;
}
return super.onOptionsItemSelected(item);
}
Here is my adapter code:
I did nothing in adapter class for sharing.
public class ListViewAdapter extends BaseAdapter {
public ArrayList<all_memories_getter_setter>list;
Activity activity;
/////**///// multiple delete
private SparseBooleanArray mSelectedItemsIds;
public ListViewAdapter(Activity activity,
ArrayList<all_memories_getter_setter>list)
{
super();
mSelectedItemsIds= new SparseBooleanArray();
this.activity=activity;
this.list=list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public Object getItem(int position) {
return list.get(position);
}
#Override
public long getItemId(int position) {
return 0;
}
/////**/////// for multiple delete
public void remove(all_memories_getter_setter object){
list.remove(object);
notifyDataSetChanged();
}
public List<all_memories_getter_setter> getall_memories_getter_setter(){
return list;
}
public void toggleSelection(int position){
selectView(position, !mSelectedItemsIds.get(position));
}
public void removeSelection(){
mSelectedItemsIds = new SparseBooleanArray();
notifyDataSetChanged();
}
public void selectView(int position , boolean value){
if(value){
mSelectedItemsIds.put(position, value);
}else{
mSelectedItemsIds.delete(position);
notifyDataSetChanged();
}
}
public int getSelectedCount(){
return mSelectedItemsIds.size();
}
public SparseBooleanArray getSelectedIds(){
return mSelectedItemsIds;
}
public class Viewholder
{
TextView txtFirst;
TextView txtSecond;
TextView txtThird;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
Viewholder holder;
LayoutInflater inflater = activity.getLayoutInflater();
if (convertView == null) {
convertView =
inflater.inflate(R.layout.activity_all_memories_listview, null);
holder = new Viewholder();
holder.txtFirst = (TextView)
convertView.findViewById(R.id.list_date);
holder.txtSecond = (TextView)
convertView.findViewById(R.id.list_title);
holder.txtThird = (TextView)
convertView.findViewById(R.id.list_content);
convertView.setTag(holder);
} else {
holder = (Viewholder) convertView.getTag();
}
holder.txtFirst.setText("" + list.get(position).getDate());
holder.txtSecond.setText("" + list.get(position).getTitle());
holder.txtThird.setText("" + list.get(position).getContent());
return convertView;
}
}
Please follow this steps to share the listview items content to other apps or within app
you can write your own method inside the getview() method of ListviewAdapter Class
Ex :
public class ListViewTestFiveActivity extends Activity{
private ListView listView;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_list_view_test_five);
init();
}
private void init() {
listView = (ListView)findViewById(R.id.ListViewTestFiveActivity_listView);
ArrayList<Item> items = new ArrayList<>();
for (int i = 0; i < 15; i++) {
Item item = new Item();
item.setCount(i);
items.add(item);
}
MyAdapter adapter = new MyAdapter(getApplicationContext(), R.layout.single_item_listview_five, items);
listView.setAdapter(adapter);
}
private class MyAdapter extends ArrayAdapter{
private ArrayList<Item> items;
private Context a_context;
private LayoutInflater a_layoutInflater;
public MyAdapter(Context context, int resource, ArrayList<Item> items) {
super(context, resource, items);
this.a_context = context;
this.items = items;
a_layoutInflater = LayoutInflater.from(this.a_context);
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
View row = convertView;
ViewHolder holder = null;
if (row == null) {
row = a_layoutInflater.inflate(R.layout.single_item_listview_five, parent, false);
holder = new ViewHolder();
holder.share = (Button) row.findViewById(R.id.ListViewTestFiveActivity_share_button);
row.setTag(holder);
} else {
holder = (ViewHolder) row.getTag();
}
final Item item = items.get(position);
holder.share.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
//Here you can write your own code to share the data, item has the data which you want to share
}
});
return row;
}
private class ViewHolder{
Button share;
}
}
private class Item {
int count;
public int getCount() {
return count;
}
public void setCount(int count) {
this.count = count;
}
}
}
Let me know if it works you or not

How to set checked value on checkbox when click listview data

My listview data have imageview , textview and checkbox. When I click listview data , everything is work .But checkbox value is not change . I want to implement as native android multi selected item. I want to apply onClick event not only checkbox but also imageview and textview. i.e it is effected that user click everywhere on one row
This is my code.
public class ProductListChkAdapter extends BaseAdapter {
private Context mContext;
private static CashSaleProductInfo _CashSaleProductInfo = null;
private List<CashSaleProductInfo> _listChkCashSaleProductInfo;
private int chkPrdcodeID;
private LayoutInflater inflater;
public static List<CashSaleListInfo> _listCashSaleListInfo;
private CashSaleProductLogic _sellProductLogic;
boolean[] checkBoxState;
private LayoutInflater layoutInflater;
public ProductListChkAdapter(Context paramContext,
List<CashSaleProductInfo> paramList1, int textViewResourceId) {
this.mContext = paramContext;
this._listChkCashSaleProductInfo = paramList1;
this.chkPrdcodeID = textViewResourceId;
checkBoxState = new boolean[_listChkCashSaleProductInfo.size()];
}
#Override
public int getCount() {
return (_listChkCashSaleProductInfo == null) ? 0
: _listChkCashSaleProductInfo.size();
}
#Override
public Object getItem(int arg0) {
return null;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(final int position, View convertView,
ViewGroup paramViewGroup) {
inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
ViewHolder viewHolder = null;
if (convertView == null) {
convertView = inflater.inflate(R.layout.productinfochklist, null);
TextView lblProductCode = (TextView) convertView
.findViewById(R.id.lblProductCode);
CheckBox chkPrdCode = (CheckBox) convertView
.findViewById(R.id.chkProductCode);
ImageView imgPrdCode = (ImageView) convertView
.findViewById(R.id.main_list_item_pcode);
RelativeLayout _relPrdlist = (RelativeLayout) convertView
.findViewById(R.id.relPrdlist);
imgPrdCode.setImageResource(R.drawable.c_f);
viewHolder = new ViewHolder();
viewHolder.lblProductCode = lblProductCode;
viewHolder.chkPrdCode = chkPrdCode;
viewHolder._relPrdlist = _relPrdlist;
convertView.setTag(viewHolder);
} else {
viewHolder = (ViewHolder) convertView.getTag();
}
viewHolder.lblProductCode.setText(_listChkCashSaleProductInfo
.get(position).getDESC_ENG().toString());
viewHolder.chkPrdCode.setChecked(checkBoxState[position]);
viewHolder._relPrdlist.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
MainActivity._CashSaleProductInfo = new CashSaleProductInfo();
// CheckBox cb = (CheckBox) v;
CheckBox cb = (CheckBox) v;
int p = position;
boolean b = checkBoxState[p];
// if (((CheckBox) v).isChecked()) {
if (!checkBoxState[position]) {
// if (cb.isChecked()) {
checkBoxState[position] = true;
// States _state = (States) cb.getTag();
MainActivity._CashSaleProductInfo
.setPRODUCT_CODE(_listChkCashSaleProductInfo.get(
position).getPRODUCT_CODE());
MainActivity._CashSaleProductInfo
.setDESC_ENG(_listChkCashSaleProductInfo.get(
position).getDESC_ENG());
MainActivity._listchkCashSaleProductInfo
.add(MainActivity._CashSaleProductInfo);
} else {
MainActivity._CashSaleProductInfo
.setPRODUCT_CODE(_listChkCashSaleProductInfo.get(
position).getPRODUCT_CODE());
MainActivity._CashSaleProductInfo
.setDESC_ENG(_listChkCashSaleProductInfo.get(
position).getDESC_ENG());
Iterator<CashSaleProductInfo> iterator = MainActivity._listchkCashSaleProductInfo
.iterator();
while (iterator.hasNext()) {
CashSaleProductInfo _CashSaleProductInfo = iterator
.next();
if (_CashSaleProductInfo.getPRODUCT_CODE().equals(
MainActivity._CashSaleProductInfo
.getPRODUCT_CODE())) {
iterator.remove();
} else {}
}
checkBoxState[position] = false;
Log.i("CC", " After "
+ MainActivity._listchkCashSaleProductInfo.size());
}
}
});
return convertView;
}
public static class ViewHolder {
TextView lblProductCode;
CheckBox chkPrdCode;
ImageView imgPrdCode;
RelativeLayout _relPrdlist;
}
}
Try add this code inside onClick to your checkbox:
cb.setChecked(true);
or
cb.setChecked(false);
try to add to Check Box setOnCheckedChangeListener
where you can store state of your CheckBox
also here Link Try this

How to disable & enable radio buttons in custom listview in android

![enter image description here][1]I've custom ListView of RadioButton & Text per line. How could i disable & enable RadioButtons clicks in ListView(i.e). How could I disable & enable selecting ListView RadioButtons by ENABLE & DISABLE Button clicks.Below is my code.
How could i do tht?
ListView LSOne;
Button lock, unlock;
int[] _intRadio = new int[20];
String[] planets = new String[] { "Mercury", "Venus", "Earth", "Mars",
"Jupiter", "Saturn", "Uranus", "Neptune" };
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LSOne = (ListView) findViewById(R.id.listView1);
lock = (Button) findViewById(R.id.lock);
unlock = (Button) findViewById(R.id.unlock);
lock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
**LsAdapter.isEnabled = !LsAdapter.isEnabled;
int first = LSOne.getFirstVisiblePosition();
for (int i = first; LSOne.getChildAt(i) != null; i++) {
RadioButton button = ((RadioButton) LSOne.getChildAt(i)
.findViewById(R.id.radioButton1));
button.setEnabled(LsAdapter.isEnabled);**
}
});
unlock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
//need to do enable option
}
});
ArrayList<String> planetList = new ArrayList<String>();
planetList.addAll(Arrays.asList(planets));
// Create ArrayAdapter using the planet list.
LsAdapter listAdapter = new LsAdapter(this, R.layout.country_info,
planetList);
LSOne.setAdapter(listAdapter);
}
public class LsAdapter extends ArrayAdapter<String> {
private LayoutInflater mInflater;
private String[] mTaxi = null;
private String[] mid = null;
long id;
**public boolean isEnabled;**
private int mViewResourceId;
public LsAdapter(Context ctx, int viewResourceId,
ArrayList<String> planetList) {
super(ctx, viewResourceId);
mInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
String[] tax = planetList.toArray(new String[planetList.size()]);
mTaxi = tax;
mViewResourceId = viewResourceId;
}
#Override
public int getCount() {
return mTaxi.length;
}
#Override
public String getItem(int position) {
return mTaxi[position];
}
#Override
public long getItemId(int position) {
return 0;
}
#Override
public int getViewTypeCount() {
// TODO Auto-generated method stub
return 20;
}
#Override
public int getItemViewType(int position) {
// TODO Auto-generated method stub
return position;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
Log.v("ConvertView", String.valueOf(position));
int _intPosition = getItemViewType(position);
if (convertView == null) {
LayoutInflater vi = (LayoutInflater) getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = vi.inflate(R.layout.country_info, null);
holder = new ViewHolder();
holder.code = (TextView) convertView
.findViewById(R.id.textView1);
holder.name = (RadioButton) convertView
.findViewById(R.id.radioButton1);
convertView.setTag(holder);
holder.code.setText(mTaxi[position]);
holder.name.setId(_intPosition);
**if (isEnabled) {
holder.name.setEnabled(true);
} else if (!isEnabled) {
holder.name.setEnabled(false);
}**
holder.name.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
for (int i = 0; i < _intRadio.length; i++) {
if (i == v.getId()) {
_intRadio[i] = 1;
} else {
_intRadio[i] = 0;
}
}
notifyDataSetChanged();
}
});
} else {
holder = (ViewHolder) convertView.getTag();
}
if (_intRadio[_intPosition] == 1) {
holder.name.setChecked(true);
} else {
holder.name.setChecked(false);
}
return convertView;
}
private class ViewHolder {
TextView code;
RadioButton name;
Button btn;
}
}
Thanks.
You don't have to write two different lock/unlock implementations. You can create a public boolean variable in LsAdapter so that LSOne can toggle it:
public class LsAdapter extends ArrayAdapter<String> {
...
public boolean isEnabled;
#Override
public View getView(int position, View convertView, ViewGroup parent) {
...
if(isEnabled)
//enable or disable the radio button here
}
Then, create an onClickListener like this:
lock = (Button) findViewById(R.id.lock);
lock.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View arg0) {
LsAdapter.isEnabled = !LsAdapter.isEnabled;
int first = LSOne.getFirstVisiblePostition();
for(int i=first; LSOne.getChildAt(i)!=null; i++) {
RadioButton button = ((RadioButton) LSOne.getChildAt(i).findViewById(your_radio_button_id));
button.setEnabled(LsAdapter.isEnabled);
}
}
});
btn.setEnabled(false); //to disable
btn.setEnabled(true); //to enable
Sometimes it don't stop multi/fast-tap on some devices so alternative option is
btn.setClickable(false); //to disable
btn.setClickable(true); //to enable

android checkbox is not checked for custom listview when listview is in scrollview

i have implemented custom list view with check box and textviews. It is working fine when list view is not in scroll but if the rows are increased then listviews is in scroll view that time when i click on check box the checked mark is not staying. here is my code, Please suggest me if anything wrong in that code
public class ArchivedAdapter extends ArrayAdapter<MessageBean> {
final ArrayList<MessageBean> updatedList = new ArrayList<MessageBean>();
private List<MessageBean> list;
private TextView officenameView, sentOnView, messageView;
public final static String MY_ACTION = "com.android.threeptalk.broadcast";
private boolean isDeleted = false;
int count = 0;
HashMap<Integer, CheckBox> checkList = new HashMap<Integer, CheckBox>();
public ArchivedAdapter(Context context, int resourseID,
List<MessageBean> list) {
super(context, resourseID, list);
this.list = list;
}
#Override
public int getCount() {
return list.size();
}
#Override
public MessageBean getItem(int arg0) {
return list.get(arg0);
}
#Override
public long getItemId(int arg0) {
return arg0;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View row = convertView;
LayoutInflater inflater = (LayoutInflater) this.getContext()
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
row = inflater.inflate(R.layout.archievedmsgrow, parent, false);
row.setId(position);
Object obj = getItem(position);
if (obj instanceof MessageBean) {
final MessageBean message = (MessageBean) obj;
CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
officenameView = (TextView) row.findViewById(R.id.officename);
sentOnView = (TextView) row.findViewById(R.id.time);
messageView = (TextView) row.findViewById(R.id.message);
officenameView.setText(message.getOfficeName());
checkList.put(position, checkBox);
checkBox.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
CheckBox c = (CheckBox) v;
if (c.isChecked()) {
c.setChecked(true);
count++;
updatedList.add(message);
} else {
c.setChecked(false);
count--;
updatedList.remove(message);
updatedList.size());
}
checkedCount(count, updatedList);
}
});
row.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
rowclicked(message, position);
}
});
sentOnView.setText(Common.getAppropriateTimeUsingTimeZone(message
.getmDate()));
if (message.getMessage() != null) {
messageView.setText((message.getMessage()));
} else {
if (message.getMessageType().equals("OPTION")) {
if (message.getOptions() != null
&& message.getOptions().size() > 0) {
String data = message.getOptions().get(0);
if (data != null && !data.equals("")) {
messageView.setText(data);
}
}
}
}
}
return row;
}
protected void messageSelected() {
}
protected void rowclicked(MessageBean message, int position) {
// TODO Auto-generated method stub
}
protected void checkedCount(int count2, ArrayList<MessageBean> updatedList) {
}
}
`
Try this example ListView with CheckBox Scrolling Issue
Seems like you are checking the check status of checkbox inside its onClickListener().
First define an Hashmap or SparseBooleanArray to save your selections.
private HashMap<Integer, Boolean> mSelection = new HashMap<Integer, Boolean>();
Then add the following code to your getView() method.
CheckBox checkBox = (CheckBox) row.findViewById(R.id.checkBox);
checkBox.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
mSelection.put(position, isChecked);
}
});
if (mSelection.get(position) != null) {
if (mSelection.get(position))
checkBox.setChecked(true);
else
checkBox.setChecked(false);
}
Try this, Assuming that you are using the Custom Adapter for your ListView, you will be able to set Tag for each Item inside your Adapter's getView(),
public View getView(int position, View convertView, ViewGroup parent) {
EvenViewHolder holdereven;
if (convertView == null) {
convertView = mInfaltor.inflate(R.layout.schedule_adapter_view,
null);
holdereven = new EvenViewHolder();
holdereven.time = (TextView) convertView
.findViewById(R.id.time);
holdereven.title = (TextView) convertView
.findViewById(R.id.title);
holdereven.des = (TextView) convertView.findViewById(R.id.des);
convertView.setTag(holdereven);
} else {
holdereven = (EvenViewHolder) convertView.getTag();
}
static class EvenViewHolder {
TextView time, title, des;
}
}

Categories

Resources