I am a French student, sorry for my mistakes.
I have to do a major project of 6 months to validate my studies. This project consists of creating an Android application.
My application consists of a listView with a custom adapter (TextView and CheckBox).
My problem is that I want to check a CheckBox that is not in the current view of my listView. For example if I want to check a checkbox at the bottom of the list and I am at the top of it (it is not visible on the screen). The checkbox check is not the right one, it ticks one randomly in the current view.
Picture ListView
Here is the view code:
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
View view = convertView;
if (view == null) {
LayoutInflater inflater = (LayoutInflater) selectActivity.getBaseContext().getSystemService(Context.LAYOUT_INFLATER_SERVICE);
view = inflater.inflate(R.layout.station_list_item, null);
}
//Handle TextView and display string from your list
TextView textViewListNomStation = (TextView)view.findViewById(R.id.textViewListNomStation);
//Log.i(tag, "nom :" +infosStationsCapteurs.cInfosStationArrayList.get(position).getNomStation() );
textViewListNomStation.setText(infosStationsCapteurs.getcInfosStationArrayList().get(position).getNomStation() + " ID : " + infosStationsCapteurs.getcInfosStationArrayList().get(position).getIdStation());
TextView textViewListInfosStation = (TextView)view.findViewById(R.id.textViewListInfosStation);
String formatInfos = "Lat : " + infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().getLatitude() + " Lon : " + infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().getLongitude();
textViewListInfosStation.setText(formatInfos);
//Handle buttons and add onClickListeners
CheckBox checkBoxStation = (CheckBox) view.findViewById(R.id.checkBoxStation);
checkBoxTab[position] = checkBoxStation;
checkBoxTab[position].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// Log.i(tag, "Bouton :" + buttonView.getId() + " Status " + isChecked);
if (isChecked == true)
{
mCheckedState[position]=true;
selectActivity.getTableauCapteurs().addHashSetstationChecked((cInfosStation)getItem(position));
selectActivity.getTableauCapteurs().createTable();
}
if (isChecked == false){
mCheckedState[position]=false;
selectActivity.getTableauCapteurs().deleteHashSetstationChecked((cInfosStation)getItem(position));
selectActivity.getTableauCapteurs().createTable();
}
}
});
checkBoxTab[position].setChecked(mCheckedState[position]);
return view;
}
Here is the code that allows me to check a checkbox in the listView
public void checkListStation(int id, boolean etat)
{
//Log.i(tag,"CheckListStation : NBR STATION : " + infosStationsCapteurs.getcInfosStationArrayList().size());
for (int i = 0;i<infosStationsCapteurs.getcInfosStationArrayList().size();i++)
{
//Log.i(tag, "CHECK " + infosStationsCapteurs.getcInfosStationArrayList().get(i).getNomStation() + " : "+name);
if (infosStationsCapteurs.getcInfosStationArrayList().get(i).getIdStation()==id)
{
mCheckedState[i]=etat;
if (checkBoxTab[i]!=null)
{
checkBoxTab[i].setChecked(etat);
Log.i(tag, "Checkbox : " + i + " : " + checkBoxTab[i].isChecked() + "taille : " + checkBoxTab.length);
}
}
}
this.notifyDataSetChanged();
}
Here is an image that shows the problem. If I want to check the one down it will check the top one instead:
Example
I hope I have been clear enough.
Thank you very much for your help.
Can you post the picture of what you want to do?It is not clear.
But what I think you want one listview which have multiple items and each item holds one checkbox.If it is then you can do it by using custom listview with adapter.
You can refer below caode
public class GeneratedOrderListAdapter extends BaseAdapter {
Context mContext;
ViewHolder holder;
Typeface tf_bold, tf_regular;
ArrayList<GenerateOrder> arrayListgeneratOrder;
public GeneratedOrderListAdapter(Context context, ArrayList<GenerateOrder> arrayListgeneratOrder) {
mContext = context;
this.arrayListgeneratOrder = new ArrayList<>();
this.arrayListgeneratOrder = arrayListgeneratOrder;
this.tf_bold = Typeface.createFromAsset(mContext.getAssets(), "opensans_semibold.ttf");
this.tf_regular = Typeface.createFromAsset(mContext.getAssets(), "opensans_regular.ttf");
}
#Override
public int getCount() {
return arrayListgeneratOrder.size();
}
#Override
public Object getItem(int i) {
return null;
}
#Override
public long getItemId(int i) {
return 0;
}
static class ViewHolder {
TextView mOrderNO;
TextView mCustomerName;
TextView mStatus;
TextView mTotalAmount;
TextView mtextOrderNO;
TextView mtextCustomerName;
TextView mtextStatus;
TextView mtextTotalAmount;
RelativeLayout relback;
}
#Override
public View getView(int position, View view, ViewGroup viewGroup) {
LayoutInflater mInflater = (LayoutInflater) mContext.getSystemService(Activity.LAYOUT_INFLATER_SERVICE);
if (view == null) {
view = mInflater.inflate(R.layout.order_list, null);
holder = new ViewHolder();
holder.mtextStatus = (TextView) view.findViewById(R.id.txt_t_status);
holder.mtextOrderNO = (TextView) view.findViewById(R.id.txt_title_orderno);
holder.mtextCustomerName = (TextView) view.findViewById(R.id.txt_t_customer);
holder.mtextTotalAmount = (TextView) view.findViewById(R.id.txt_t_amount);
holder.mStatus = (TextView) view.findViewById(R.id.txt_status);
holder.mOrderNO = (TextView) view.findViewById(R.id.txt_orderno);
holder.mCustomerName = (TextView) view.findViewById(R.id.txt_customer);
holder.mTotalAmount = (TextView) view.findViewById(R.id.txt_amount);
holder.relback=(RelativeLayout)view.findViewById(R.id.rel_back);
// setTypeFace();
view.setTag(holder);
} else {
holder = (ViewHolder) view.getTag();
}
try {
holder.mStatus.setText(arrayListgeneratOrder.get(position).getOrderStatus());
holder.mTotalAmount.setText(arrayListgeneratOrder.get(position).getAmount());
holder.mCustomerName.setText(arrayListgeneratOrder.get(position).getCustomerName());
holder.mOrderNO.setText(arrayListgeneratOrder.get(position).getOrderNo());
if(position%2==0){
holder.relback.setBackgroundColor(Color.parseColor("#f4fff5"));
}else{
holder.relback.setBackgroundColor(Color.parseColor("#ffffff"));
}
} catch (Exception e) {
e.printStackTrace();
}
return view;
}
private void setTypeFace() {
holder.mStatus.setTypeface(tf_regular);
holder.mTotalAmount.setTypeface(tf_regular);
holder.mCustomerName.setTypeface(tf_regular);
holder.mOrderNO.setTypeface(tf_regular);
holder.mtextStatus.setTypeface(tf_regular);
holder.mtextOrderNO.setTypeface(tf_regular);
holder.mtextCustomerName.setTypeface(tf_regular);
holder.mtextTotalAmount.setTypeface(tf_regular);
}
}
In your model class add CheckFlag paramter and initialize to zero
//Handle buttons and add onClickListeners
CheckBox checkBoxStation = (CheckBox) view.findViewById(R.id.checkBoxStation);
int check_flag=infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().getCheckFlag();
if(check_flag==1)
{
checkBoxStation.setChecked(true);
}
else
{
checkBoxStation.setChecked(false);
}
checkBoxStation.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Log.i(tag, "Bouton :" + buttonView.getId() + " Status " + isChecked);
if (isChecked)
{
infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().setCheckFlag(1);
}
else{
{
infosStationsCapteurs.getcInfosStationArrayList().get(position).getPositionGPS().setCheckFlag(0);
}
notifyDataSetChanged();
}
});
Use the code below.
This is adater class
public class AttendanceAdapter extends BaseAdapter{
Context ctx;
LayoutInflater lInflater;
ArrayList<Student> objects;
public AttendanceAdapter(Context context, ArrayList<Student> students) {
ctx = context;
objects = students;
lInflater = (LayoutInflater) ctx
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
}
#Override
public int getCount() {
return objects.size();
}
#Override
public Object getItem(int position) {
return objects.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) {
view = lInflater.inflate(R.layout.atndnc_items, parent, false);
}
Student s = getStudent(position);
((TextView) view.findViewById(R.id.txtRollno)).setText(s.rollno);
((TextView) view.findViewById(R.id.txtName)).setText(s.fname+" "+s.mname+" "+s.lname);
final CheckBox cbAtnd = (CheckBox) view.findViewById(R.id.chckTick);
cbAtnd.setOnCheckedChangeListener(myCheckChangList);
cbAtnd.setTag(position);
cbAtnd.setChecked(s.chck);
return view;
}
Student getStudent(int position) {
return ((Student) getItem(position));
}
public ArrayList<Student> getBox() {
ArrayList<Student> box = new ArrayList<Student>();
for (Student s : objects) {
box.add(s);
}
return box;
}
CompoundButton.OnCheckedChangeListener myCheckChangList = new CompoundButton.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
getStudent((Integer) buttonView.getTag()).chck = isChecked;
}
};}
Then create one object of your adater and call this method from your main activity.Here boxadater is the object of my Adapter class.
public void getValue(){
for (Student s :boxAdapter.getBox()) {
attendance.attendancelist.add(new Attendance( s.rollno,s.fname+" "+s.mname+" "+s.lname,s.chck));
}
}
Related
I am calling three JSONRequests with Volley and this method is called at every response of the request. This method only is executed when all three responses are ready. But when I try to update the expandable list it fails to display on the screen. Could anyone see if I am doing something wrong?
private void updateWhenReady(){
System.out.println(validCurrent+ " " + validDaily + " " + validHourly );
if(validCurrent && validDaily && validHourly)
{
System.out.println("in");
for (WeatherCondition wc: dailyResponseList)
{
ArrayList<WeatherCondition> tempList = new ArrayList<>();
for(WeatherCondition w: hourlyResponseList)
{
if(w.getDate().equalsIgnoreCase(wc.getDate()))
{
tempList.add(w);
}
}
weatherList.put(wc,tempList);
}
for (WeatherCondition weatherCondition: weatherList.keySet())
{
System.out.println(" + " + weatherCondition.getDate());
}
weatherList = dbHelper.getWeatherConditionsHashMap();
hourlyList = new ArrayList<WeatherCondition>(weatherList.keySet());
adapter = new WeatherSearchListAdapter(getActivity().getApplicationContext(), weatherList, hourlyList);
expList.setAdapter(adapter);
adapter.notifyDataSetChanged();
System.out.println(validCurrent + " " + validDaily + " " + validHourly);
validCurrent = false;
validDaily = false;
validHourly = false;
}
}
and the following is the explist adapter
public class WeatherSearchListAdapter extends BaseExpandableListAdapter {
private Context ctx;
private HashMap<WeatherCondition, List<WeatherCondition>> weatherList;
private List<WeatherCondition> list;
public WeatherSearchListAdapter(Context ctx, HashMap<WeatherCondition, List<WeatherCondition>> parentList, List<WeatherCondition> list){
this.weatherList = parentList;
this.list = list;
this.ctx = ctx;
};
#Override
public int getGroupCount() {
return list.size();
}
#Override
public int getChildrenCount(int groupPosition) {
return weatherList.get(list.get(groupPosition)).size();
}
#Override
public Object getGroup(int groupPosition) {
return list.get(groupPosition);
}
#Override
public Object getChild(int parent, int child) {
return weatherList.get(list.get(parent)).get(child);
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public long getChildId(int parent, int child) {
return child;
}
#Override
public boolean hasStableIds() {
return false;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded, View convertView, ViewGroup parent) {
WeatherCondition groupWeatherCondition = (WeatherCondition) getGroup(groupPosition);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.fragment_daily_list_parent, parent, false);
}
ImageView weatherIconIdIV = (ImageView) convertView.findViewById(R.id.weatherIconIV);
ImageView windIconIdIV = (ImageView) convertView.findViewById(R.id.windDirectionIV);
TextView humidityTV = (TextView) convertView.findViewById(R.id.humitityListText);
TextView rainTV = (TextView) convertView.findViewById(R.id.rainListText);
TextView windDirectionTV = (TextView) convertView.findViewById(R.id.windDirectionText);
TextView windSpeedTV = (TextView) convertView.findViewById(R.id.windSpeedText);
TextView maxTempTV = (TextView) convertView.findViewById(R.id.maxTempListText);
TextView minTempTV = (TextView) convertView.findViewById(R.id.minTempListText);
TextView dateTV = (TextView) convertView.findViewById(R.id.dateListText);
String name = groupWeatherCondition.getWeatherIconId();
int weatherIconId = ctx.getResources().getIdentifier(name, "drawable", ctx.getPackageName());
weatherIconIdIV.setImageResource(weatherIconId);
String name1 = groupWeatherCondition.getWind().getWindIconId();
int windIconId = ctx.getResources().getIdentifier(name1, "drawable", ctx.getPackageName());
windIconIdIV.setImageResource(windIconId);
humidityTV.setText(groupWeatherCondition.getHumidity());
rainTV.setText(groupWeatherCondition.getRain());
windDirectionTV.setText(groupWeatherCondition.getWind().getWindDirection());
windSpeedTV.setText(groupWeatherCondition.getWind().getSpeed());
maxTempTV.setText(groupWeatherCondition.getMaxTemp());
minTempTV.setText(groupWeatherCondition.getMinTemp());
dateTV.setText(groupWeatherCondition.getDate());
convertView.setBackgroundColor(Color.parseColor("#5E5E5E"));
return convertView;
}
#Override
public View getChildView(int parent, int child, boolean isLastChild, View convertView, ViewGroup parentView) {
WeatherCondition childWeatherCondition = (WeatherCondition) getChild(parent, child);
if(convertView == null)
{
LayoutInflater inflator = (LayoutInflater) ctx.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflator.inflate(R.layout.fragment_daily_list_parent, parentView, false);
}
ImageView weatherIconIdIV = (ImageView) convertView.findViewById(R.id.weatherIconIV);
ImageView windIconIdIV = (ImageView) convertView.findViewById(R.id.windDirectionIV);
TextView humidityTV = (TextView) convertView.findViewById(R.id.humitityListText);
TextView rainTV = (TextView) convertView.findViewById(R.id.rainListText);
TextView windDirectionTV = (TextView) convertView.findViewById(R.id.windDirectionText);
TextView windSpeedTV = (TextView) convertView.findViewById(R.id.windSpeedText);
TextView maxTempTV = (TextView) convertView.findViewById(R.id.maxTempListText);
TextView minTempTV = (TextView) convertView.findViewById(R.id.minTempListText);
TextView dateTV = (TextView) convertView.findViewById(R.id.dateListText);
String name = childWeatherCondition.getWeatherIconId();
int weatherIconId = ctx.getResources().getIdentifier(name, "drawable", ctx.getPackageName());
weatherIconIdIV.setImageResource(weatherIconId);
String name1 = childWeatherCondition.getWind().getWindIconId();
int windIconId = ctx.getResources().getIdentifier(name1, "drawable", ctx.getPackageName());
windIconIdIV.setImageResource(windIconId);
humidityTV.setText(childWeatherCondition.getHumidity());
rainTV.setText(childWeatherCondition.getRain());
windDirectionTV.setText(childWeatherCondition.getWind().getWindDirection());
windSpeedTV.setText(childWeatherCondition.getWind().getSpeed());
maxTempTV.setText(childWeatherCondition.getMaxTemp());
minTempTV.setText(childWeatherCondition.getMinTemp());
dateTV.setText(childWeatherCondition.getDate());
return convertView;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
Do the variable initializations before the logic starts -
private void updateWhenReady(){
System.out.println(validCurrent+ " " + validDaily + " " + validHourly );
weatherList = dbHelper.getWeatherConditionsHashMap();
hourlyList = new ArrayList<WeatherCondition>(weatherList.keySet());
adapter = new WeatherSearchListAdapter(getActivity().getApplicationContext(), weatherList, hourlyList);
System.out.println(validCurrent + " " + validDaily + " " + validHourly);
if(validCurrent && validDaily && validHourly)
{
System.out.println("in");
for (WeatherCondition wc: dailyResponseList)
{
ArrayList<WeatherCondition> tempList = new ArrayList<>();
for(WeatherCondition w: hourlyResponseList)
{
if(w.getDate().equalsIgnoreCase(wc.getDate()))
{
tempList.add(w);
}
}
weatherList.put(wc,tempList);
}
for (WeatherCondition weatherCondition: weatherList.keySet())
{
System.out.println(" + " + weatherCondition.getDate());
}
//Do you need to reset these? What if only two of the three were true?
validCurrent = false;
validDaily = false;
validHourly = false;
}
}
expList.setAdapter(adapter);
/* If you are setting adapter every time *updateWhenReady* is invoked, no need to notifyDataSetChanged, because its a new adapter and layout will be drawn fresh */
//adapter.notifyDataSetChanged();
}
In getChildView
inflate using fragment_daily_list_parent
copy-past error?
hi friends i am not able to understand how to set text in the same row of the list view where i am having two button with text view at the center but when i am trying to increment or decrement the effect is showing on the next row but not the row on which i want the changes to be applied
CartAdapter.java
public class Cart_Adapter extends BaseAdapter {
Context cartcontext;
List<MobiData> cartlist;
LayoutInflater inflater;
cartlist cartdata;
public ArrayList<Integer> quantity = new ArrayList<Integer>();
CustomButtonListener customButtonListener;
public Cart_Adapter(Context cartcontext, List<MobiData> cartlist) {
this.cartcontext = cartcontext;
this.cartlist = cartlist;
}
#Override
public int getCount() {
return cartlist.size();
}
#Override
public Object getItem(int position) {
return cartlist.get(position);
}
#Override
public long getItemId(int position) {
return position;
}
#Override
public View getView(final int position, View convertView, ViewGroup parent) {
inflater = (LayoutInflater) cartcontext.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
if (convertView == null) {
cartdata = new cartlist();
convertView = inflater.inflate(R.layout.cart_row, parent, false);
cartdata.decrement = (TextView) convertView.findViewById(R.id.decrement);
cartdata.single = (TextView) convertView.findViewById(R.id.single);
cartdata.single.setTag(position);
cartdata.increment = (TextView) convertView.findViewById(R.id.increment);
cartdata.increment.setTag(position);
cartdata.cancel = (TextView) convertView.findViewById(R.id.cancel);
cartdata.vcmedname = (TextView) convertView.findViewById(R.id.vcmedname);
cartdata.vcmedprice = (TextView) convertView.findViewById(R.id.vcmedprice);
Typeface carttext = Typeface.createFromAsset(cartcontext.getAssets(), "fonts/fontawesome.ttf");
cartdata.decrement.setTypeface(carttext);
cartdata.increment.setTypeface(carttext);
cartdata.cancel.setTypeface(carttext);
convertView.setTag(cartdata);
} else {
cartdata = (cartlist) convertView.getTag();
}
MobiData newcart = cartlist.get(position);
cartdata.vcmedname.setText(newcart.getVcmedname());
cartdata.vcmedprice.setText(newcart.getVcmedprice());
cartdata.single.setText(newcart.getVcqty());
final String cartids = newcart.getVcmedid();
cartdata.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartlist.remove(position);
notifyDataSetChanged();
}
});
cartdata.increment.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick( View v) {
if (customButtonListener !=null){
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
cartdata.single.setText(String.valueOf(plus));
SharedPreferences viewpref = cartcontext.getSharedPreferences("datapref", Context.MODE_PRIVATE);
String cartuid = viewpref.getString("uid", "");
String carttempid = viewpref.getString("tempid", "");
String incremnturl = "http://sampletemplates.net/mobichemist/json/cart_process.php?mid=" + cartids + "&userid=" + cartuid + "&tempid=" + carttempid;
Log.d("Incremnturl", incremnturl);
JsonArrayRequest incrementarray = new JsonArrayRequest(Request.Method.GET, incremnturl, (String) null, new Response.Listener<JSONArray>() {
#Override
public void onResponse(JSONArray response) {
for (int i = 0; i < response.length(); i++) {
try {
JSONObject incrobj = response.getJSONObject(i);
int plus = Integer.parseInt(cartdata.single.getText().toString());
plus++;
cartdata.single.setText(String.valueOf(plus));
} catch (JSONException e) {
e.printStackTrace();
}
}
}
}, new Response.ErrorListener() {
#Override
public void onErrorResponse(VolleyError error) {
Log.d("Incrementurl", String.valueOf(error));
}
});
incrementarray.setRetryPolicy(new DefaultRetryPolicy(50000, DefaultRetryPolicy.DEFAULT_MAX_RETRIES,
DefaultRetryPolicy.DEFAULT_BACKOFF_MULT));
AppController.getInstance().addToRequestQueue(incrementarray);
}
});
cartdata.decrement.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
int i = Integer.parseInt(cartdata.single.getText().toString());
i--;
if (i <= 0) {
Toast.makeText(Single_Cart_Page.this, "Minimum Quantity is 1", Toast.LENGTH_SHORT).show();
} else {
cartdata.single.setText(String.valueOf(i));
}
}
});
return convertView;
}
static class cartlist {
TextView decrement, single, increment, cancel, vcmedname, vcmedprice;
}
try this and add your other code.
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = inflater.inflate(R.layout.cart_row, parent, false);
holder = new ViewHolder();
holder.decrement = (TextView) convertView.findViewById(R.id.decrement);
holder.single = (TextView) convertView.findViewById(R.id.single);
holder.increment = (TextView) convertView.findViewById(R.id.increment);
holder.cancel = (TextView) convertView.findViewById(R.id.cancel);
holder.vcmedname = (TextView) convertView.findViewById(R.id.vcmedname);
holder.vcmedprice = (TextView) convertView.findViewById(R.id.vcmedprice);
convertView.setTag(holder);
}
else {
holder = (ViewHolder) convertView.getTag();
}
Typeface carttext = Typeface.createFromAsset(cartcontext.getAssets(), "fonts/fontawesome.ttf");
holder.decrement.setTypeface(carttext);
holder.increment.setTypeface(carttext);
holder.cancel.setTypeface(carttext);
MobiData newcart = cartlist.get(position);
holder.vcmedname.setText(newcart.getVcmedname());
holder.vcmedprice.setText(newcart.getVcmedprice());
holder.single.setText(newcart.getVcqty());
final String cartids = newcart.getVcmedid();
holder.cancel.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
cartlist.remove(position);
notifyDataSetChanged();
}
});
return convertView;
}
static class ViewHolder {
private TextView decrement;
private TextView single;
private TextView increment;
private TextView vcmedname;
private TextView vcmedprice;
}
Use ArrayAdaper instead of Base Adapter with ViewHolder. Don't set setTag(position) manually for all views.
Find ViewHolder example here https://dzone.com/articles/optimizing-your-listview .It will solve your indexing problem. ViewHolder class sets all views position. Also find more description on Hold View Objects in a View Holder
I've loaded some pictures into a ListView using an adapter. When a user clicks on any row of the list I'm showing a checkmark at the end:
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener{
private Activity activity;
List<String> names,facebookbid;
String sent;
private LayoutInflater inflater=null;
public ImageLoader imageLoader;
public LazyImageLoadAdapter(Activity a, List<String> n,List<String> fid,String s) {
activity = a;
names=n;
facebookbid=fid;
sent=s;
inflater = (LayoutInflater)activity.
getSystemService(Context.LAYOUT_INFLATER_SERVICE);
imageLoader = new ImageLoader(activity.getApplicationContext(),"p");
}
#Override
public int getViewTypeCount() {
if (getCount() != 0)
return getCount();
return 1;
}
public int getCount() {
return facebookbid.size();
}
public Object getItem(int position) {
return position;
}
public long getItemId(int position) {
return position;
}
/********* Create a holder Class to contain inflated xml file elements *********/
public class ViewHolder{
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
convertView=null;
final ViewHolder holder;
if(convertView==null){
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = inflater.inflate(R.layout.planners_friends_listrow, null);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView)convertView.findViewById(R.id.planner_friend_image);
holder.checkmark=(ImageView)convertView.findViewById(R.id.checkmark);
holder.friendsrow=(RelativeLayout)convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag( holder );
}
else
holder=(ViewHolder)convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if(sent.equals("planners"))
{link=facebookbid.get(position);
}
else
{
link="https://graph.facebook.com/"+facebookbid.get(position)+"/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a=isNetworkConnected();
if(a==true)
{
if(sender.equals("settings"))
{
}
else if(sender.equals("savethedate"))
{
if(sid.contains(facebookbid.get(position)))
{
if(sid.contains("_"))
{
sid=sid.replace("_"+facebookbid.get(position), "");
}
else
{
sid=sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size()-1);
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.GONE);
}
else
{
if(sid.isEmpty())
{
sid=sid+facebookbid.get(position);
}
else
{
sid=sid+"_"+facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite ("+String.valueOf(nb_selections)+") friends");
holder.checkmark.setVisibility(View.VISIBLE);
}
}
else
{
String friendname=names.get(position);
String friendid=facebookbid.get(position);
String friendgender=gender.get(position);
Intent resultIntent = new Intent(Friends.this,Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if(sender.equals("planner"))
{
resultIntent.putExtra("plannerid",friendid);
resultIntent.putExtra("imageurl","https://graph.facebook.com/"+friendid+"/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
else
{
resultIntent.putExtra("plannerid","");
resultIntent.putExtra("imageurl","");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
}
else
{
Toast.makeText(getApplicationContext(),"No internet connection",Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
The problem is: When the ListView is scrolled, the checkmark icon simply disappears. What am I doing wrong?
Looking at your code you set the Visibility of the checkmark when the user clicks on one of the items which then shows / hides the item. Now when the user scrolls the items are recycled and you dont have any code to check if the item has been checked or not.
So in short you need something that basically says
if (checked) {
//set visibility of the checkmark to visible
} else {
//set visibility of the checkmark to gone
}
First you need to change getView method as don't reinitialize convertView as null remove below line from getView
public class LazyImageLoadAdapter extends BaseAdapter implements OnClickListener {
private Activity activity;
List<String> names, facebookbid;
String sent;
public ImageLoader imageLoader;
private int size = 0;
private HashMap<String, Boolean> mapClickStatus;
public LazyImageLoadAdapter(Activity a, List<String> n, List<String> fid, String s) {
activity = a;
names = n;
facebookbid = fid;
sent = s;
mapClickStatus = new HashMap<String, Boolean>();
if (facebookbid != null)
size = facebookbid.size();
// Give total size of the list item to getCount method
imageLoader = new ImageLoader(activity, "p");
}
#Override
public int getCount() {
return size;
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int position) {
return position;
}
/*********
* Create a holder Class to contain inflated xml file elements
*********/
public class ViewHolder {
public TextView text;
public ImageView image;
public ImageView checkmark;
public RelativeLayout friendsrow;
}
public View getView(final int position, View convertView, ViewGroup parent) {
// convertView=null;
//It should not be null every time
final ViewHolder holder;
if (convertView == null) {
/****** Inflate tabitem.xml file for each row ( Defined below ) *******/
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
/****** View Holder Object to contain tabitem.xml file elements ******/
holder = new ViewHolder();
holder.text = (TextView) convertView.findViewById(R.id.planner_friend_name);
(ImageView) convertView.findViewById(R.id.planner_friend_image);
holder.checkmark = (ImageView) convertView.findViewById(R.id.checkmark);
holder.friendsrow = (RelativeLayout) convertView.findViewById(R.id.friendsrow);
/************ Set holder with LayoutInflater ************/
convertView.setTag(holder);
} else
holder = (ViewHolder) convertView.getTag();
holder.text.setText(names.get(position));
Typeface face = Typeface.createFromAsset(convertView.getContext().getAssets(),
"fonts/MAXWELL REGULAR.ttf");
holder.text.setTypeface(face);
ImageView image = holder.image;
String link;
if (sent.equals("planners")) {
link = facebookbid.get(position);
} else {
link = "https://graph.facebook.com/" + facebookbid.get(position) + "/picture?type=large";
}
//DisplayImage function from ImageLoader Class
imageLoader.DisplayImage(link, image);
// set the visibility of CheckMark ImageView based on the click status.
if (mapClickStatus.get(facebookbid.get(position)))
holder.checkmark.setVisibility(View.VISIBLE);
else
holder.checkmark.setVisibility(View.GONE);
holder.friendsrow.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
boolean a = isNetworkConnected();
/// I dont know about the unique ID field in this so i took facebookbid.get(position) as a key
// To set click status of row item in hashmap.
mapClickStatus.put(facebookbid.get(position),
mapClickStatus.containsKey(facebookbid.get(position)) ? false : true);
if (a == true) {
if (sender.equals("settings")) {
} else if (sender.equals("savethedate")) {
if (sid.contains(facebookbid.get(position))) {
if (sid.contains("_")) {
sid = sid.replace("_" + facebookbid.get(position), "");
} else {
sid = sid.replace(facebookbid.get(position), "");
}
nb_selections--;
selectedids.remove(selectedids.size() - 1);
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.GONE);
} else {
if (sid.isEmpty()) {
sid = sid + facebookbid.get(position);
} else {
sid = sid + "_" + facebookbid.get(position);
}
nb_selections++;
selectedids.add(facebookbid.get(position));
sidetitle.setText("Invite (" + String.valueOf(nb_selections) + ") friends");
// holder.checkmark.setVisibility(View.VISIBLE);
}
// TO refresh view with updated checkmark status
notifyDataSetChanged();
} else {
String friendname = names.get(position);
String friendid = facebookbid.get(position);
String friendgender = gender.get(position);
Intent resultIntent = new Intent(Friends.this, Newmarriage.class);
resultIntent.putExtra("facebookbid", friendid);
resultIntent.putExtra("name", friendname);
resultIntent.putExtra("gender", friendgender);
if (sender.equals("planner")) {
resultIntent.putExtra("plannerid", friendid);
resultIntent.putExtra("imageurl", "https://graph.facebook.com/" + friendid + "/picture?type=large");
setResult(Activity.RESULT_OK, resultIntent);
finish();
} else {
resultIntent.putExtra("plannerid", "");
resultIntent.putExtra("imageurl", "");
setResult(Activity.RESULT_OK, resultIntent);
finish();
}
}
} else {
Toast.makeText(getApplicationContext(), "No internet connection", Toast.LENGTH_LONG).show();
}
}
});
/******** Set Item Click Listner for LayoutInflater for each row ***********/
// vi.setOnClickListener(new OnItemClickListener(position));
return convertView;
}
#Override
public void onClick(View arg0) {
// TODO Auto-generated method stub
}
}
Suggestions
Inflate layout with parent attaching like below
.
convertView = LayoutInflater.from(activity).inflate(R.layout.planners_friends_listrow, parent, false);
Avoid mantaining status by using multiple collection(Arraylist or
like that to display data) use Model Class or JSON or Arraylist of
map etc.
I have 2 activities with listview and when I go to activity B and back to A and click, I get error:
java.lang.IllegalStateException: The content of the adapter has changed but ListView did not receive a notification. Make sure the content of your adapter is not modified from a background thread, but only from the UI thread. Make sure your adapter calls notifyDataSetChanged() when its content changes. [in ListView(2131492961, class android.widget.ListView) with Adapter(class com.example.example.ItemListBaseAdapter)]
When I need to call notifyDataSetChanged()?
In my acticities or in ItemListBaseAdapter Class?
The code in my activities:
ArrayList<ItemDetails> image_details = GetSearchResults();
final ListView lv1 = (ListView) findViewById(R.id.list);
lv1.setAdapter(new ItemListBaseAdapter(getApplicationContext(), image_details));
lv1.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> a, View v, int position, long id) {
Object o = lv1.getItemAtPosition(position);
}
});
private ArrayList<ItemDetails> GetSearchResults() {
ArrayList<ItemDetails> results = new ArrayList<ItemDetails>();
for(int i = 0;i<Code.size();i++) {
ItemDetails item_details = new ItemDetails();
item_details.setName(getString(R.string.newanswer));
item_details.setItemDescription(Book.get(i) + " - " + getString(R.string.page) + " " + Page.get(i) + " " + getString(R.string.exercise) + " " + Exercise.get(i) + "\n" + getString(R.string.clicktoshow));
item_details.setImageNumber(2000);
results.add(item_details);
}
return results;
}
The ItemListBaseAdapter Class:
public class ItemListBaseAdapter extends BaseAdapter {
private static ArrayList<ItemDetails> itemDetailsrrayList;
private LayoutInflater l_Inflater;
public ItemListBaseAdapter(Context context, ArrayList<ItemDetails> results) {
itemDetailsrrayList = results;
l_Inflater = LayoutInflater.from(context);
}
public int getCount() {
return itemDetailsrrayList.size();
}
public Object getItem(int position) {
return itemDetailsrrayList.get(position);
}
public long getItemId(int position) {
return position;
}
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder;
if (convertView == null) {
convertView = l_Inflater.inflate(R.layout.item_details_view, null);
holder = new ViewHolder();
holder.txt_itemName = (TextView) convertView.findViewById(R.id.name);
holder.txt_itemDescription = (TextView) convertView.findViewById(R.id.itemDescription);
holder.itemImage = (ImageView) convertView.findViewById(R.id.photo);
convertView.setTag(holder);
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.txt_itemName.setText(itemDetailsrrayList.get(position).getName());
holder.txt_itemDescription.setText(itemDetailsrrayList.get(position).getItemDescription());
if(itemDetailsrrayList.get(position).getImageNumber() == 1999) {
holder.itemImage.setImageResource(R.drawable.person);
}
else {
if(itemDetailsrrayList.get(position).getImageNumber() == 2000) {
holder.itemImage.setImageResource(R.drawable.icon);
}
else {
byte[] a = itemDetailsrrayList.get(position).getPicture();
Bitmap bmp = BitmapFactory
.decodeByteArray(
a, 0,
a.length);
holder.itemImage.setImageBitmap(bmp);
}
}
return convertView;
}
static class ViewHolder {
TextView txt_itemName;
TextView txt_itemDescription;
ImageView itemImage;
}}
In my app I need to show images inside a expandableListView and it has to be a gridview of images, and these images can be selectable so I have an expandableListAdapter and inside of it I'm implementing a gridview adapter,
the images are showing fine as you can see in the picture 1, now what I'm trying to achieve is the picture 2, how can I pass the groupPosition and the childPosition to the gridAdapter and whe I click on the image make it highlight? :
Picture 2:
public class ExpandListAdapter extends BaseExpandableListAdapter {
public static final int CHOICE_MODE_MULTIPLE = AbsListView.CHOICE_MODE_MULTIPLE;
public static final int CHOICE_MODE_MULTIPLE_MODAL = AbsListView.CHOICE_MODE_MULTIPLE_MODAL;
/**
* No child could be selected
*/
public static final int CHOICE_MODE_NONE = AbsListView.CHOICE_MODE_NONE;
/**
* One single choice per group
*/
public static final int CHOICE_MODE_SINGLE_PER_GROUP = AbsListView.CHOICE_MODE_SINGLE;
/**
* One single choice for all the groups
*/
public static final int CHOICE_MODE_SINGLE_ABSOLUTE = 10001;
private Context context;
private ArrayList<Group> groups;
private ArrayList<ArrayList<Child>> child = new ArrayList();
private ArrayList<Child> listchild;
private GridAdapter adapter;
private CustomGridView gridView;
private SparseArray<SparseBooleanArray> checkedPositions;
private static final String LOG_TAG = ExpandListAdapter.class.getSimpleName();
private int choiceMode = CHOICE_MODE_MULTIPLE;
public ExpandListAdapter(Context context, ArrayList<Group> groups) {
this.context = context;
this.groups = groups;
checkedPositions = new SparseArray<SparseBooleanArray>();
child = new ArrayList();
for (int i = 0; i < groups.size(); i++) {
child.add(i, groups.get(i).getItems());
}
}
public ExpandListAdapter(Context context, ArrayList<Group> children, int choiceMode) {
this(context, children);
// For now the choice mode CHOICE_MODE_MULTIPLE_MODAL
// is not implemented
if (choiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
throw new RuntimeException("The choice mode CHOICE_MODE_MULTIPLE_MODAL " +
"has not implemented yet");
}
this.choiceMode = choiceMode;
}
#Override
public Object getChild(int groupPosition, int childPosition) {
return child.get(childPosition);
}
#Override
public long getChildId(int groupPosition, int childPosition) {
return childPosition;
}
#Override
public View getChildView(final int groupPosition, final int childPosition,
boolean isLastChild, View convertView, ViewGroup parent) {
if (convertView == null) {
LayoutInflater infalInflater = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = infalInflater.inflate(R.layout.gridview, null);
}
listchild = new ArrayList<Child>();
for (int j = 0; j < groups.get(groupPosition).getItems().size(); j++) {
listchild.add(child.get(groupPosition).get(j));
}
gridView = (CustomGridView) convertView.findViewById(R.id.GridView_toolbar);
gridView.setExpanded(true);
adapter = new GridAdapter(context, listchild, checkedPositions, groupPosition, childPosition);
gridView.setAdapter(adapter);// Adapter
gridView.setChoiceMode(CustomGridView.CHOICE_MODE_MULTIPLE);
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setClicked(groupPosition, childPosition);
System.out.println("position" + checkedPositions.get(groupPosition));
if (checkedPositions.get(groupPosition) != null) {
boolean isChecked = checkedPositions.get(groupPosition).get(childPosition);
if(!isChecked){
}
} else {
System.out.println("false");
}
}
});
return convertView;
}
public void setClicked(int groupPosition, int childPosition) {
switch (choiceMode) {
case CHOICE_MODE_MULTIPLE:
SparseBooleanArray checkedChildPositionsMultiple = checkedPositions.get(groupPosition);
// if in the group there was not any child checked
if (checkedChildPositionsMultiple == null) {
checkedChildPositionsMultiple = new SparseBooleanArray();
// By default, the status of a child is not checked
// So a click will enable it
checkedChildPositionsMultiple.put(childPosition, true);
checkedPositions.put(groupPosition, checkedChildPositionsMultiple);
} else {
boolean oldState = checkedChildPositionsMultiple.get(childPosition);
checkedChildPositionsMultiple.put(childPosition, !oldState);
}
break;
// TODO: Implement it
case CHOICE_MODE_MULTIPLE_MODAL:
throw new RuntimeException("The choice mode CHOICE_MODE_MULTIPLE_MODAL " +
"has not implemented yet");
case CHOICE_MODE_NONE:
checkedPositions.clear();
break;
case CHOICE_MODE_SINGLE_PER_GROUP:
SparseBooleanArray checkedChildPositionsSingle = checkedPositions.get(groupPosition);
// If in the group there was not any child checked
if (checkedChildPositionsSingle == null) {
checkedChildPositionsSingle = new SparseBooleanArray();
// By default, the status of a child is not checked
checkedChildPositionsSingle.put(childPosition, true);
checkedPositions.put(groupPosition, checkedChildPositionsSingle);
} else {
boolean oldState = checkedChildPositionsSingle.get(childPosition);
// If the old state was false, set it as the unique one which is true
if (!oldState) {
checkedChildPositionsSingle.clear();
checkedChildPositionsSingle.put(childPosition, !oldState);
} // Else does not allow the user to uncheck it
}
break;
// This mode will remove all the checked positions from other groups
// and enable just one from the selected group
case CHOICE_MODE_SINGLE_ABSOLUTE:
checkedPositions.clear();
SparseBooleanArray checkedChildPositionsSingleAbsolute = new SparseBooleanArray();
checkedChildPositionsSingleAbsolute.put(childPosition, true);
checkedPositions.put(groupPosition, checkedChildPositionsSingleAbsolute);
break;
}
// Notify that some data has been changed
notifyDataSetChanged();
Log.v(LOG_TAG, "List position updated");
Log.v(LOG_TAG, PrintSparseArrays.sparseArrayToString(checkedPositions));
}
public void setChoiceMode(int choiceMode) {
this.choiceMode = choiceMode;
// For now the choice mode CHOICE_MODEL_MULTIPLE_MODAL
// is not implemented
if (choiceMode == CHOICE_MODE_MULTIPLE_MODAL) {
throw new RuntimeException("The choice mode CHOICE_MODE_MULTIPLE_MODAL " +
"has not implemented yet");
}
checkedPositions.clear();
Log.v(LOG_TAG, "The choice mode has been changed. Now it is " + this.choiceMode);
}
#Override
public int getChildrenCount(int nGroup) {
return 1;
}
#Override
public Object getGroup(int groupPosition) {
return groups.get(groupPosition);
}
#Override
public int getGroupCount() {
return groups.size();
}
#Override
public long getGroupId(int groupPosition) {
return groupPosition;
}
#Override
public View getGroupView(int groupPosition, boolean isExpanded,
View convertView, ViewGroup parent) {
Group group = (Group) getGroup(groupPosition);
if (convertView == null) {
LayoutInflater inf = (LayoutInflater) context
.getSystemService(context.LAYOUT_INFLATER_SERVICE);
convertView = inf.inflate(R.layout.group_item, null);
}
ExpandableListView mExpandableListView = (ExpandableListView) parent;
mExpandableListView.expandGroup(groupPosition);
TextView tv = (TextView) convertView.findViewById(R.id.group_name);
tv.setText(group.getName());
return convertView;
}
#Override
public boolean hasStableIds() {
return true;
}
#Override
public boolean isChildSelectable(int groupPosition, int childPosition) {
return true;
}
}
GridAdapter:
public class GridAdapter extends BaseAdapter {
private Context mContext;
private ArrayList<Child> child;
ImageLoader imageLoader = AppController.getInstance().getImageLoader();
private SparseArray<SparseBooleanArray> checkedPositions;
int groupPosition, childPosition;
public GridAdapter(Context context, ArrayList<Child> childValues, SparseArray<SparseBooleanArray> checkedPositions, int groupPosition, int childPosition) {
mContext = context;
child = childValues;
this.checkedPositions = checkedPositions;
this.childPosition = childPosition;
this.groupPosition = groupPosition;
}
#Override
public int getCount() {
return child.size();
}
#Override
public Object getItem(int position) {
return position;
}
#Override
public long getItemId(int arg0) {
return 0;
}
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NetworkImageView i;
childPosition = position;
if (convertView == null) {
LayoutInflater inflater = (LayoutInflater) mContext
.getSystemService(Context.LAYOUT_INFLATER_SERVICE);
convertView = inflater.inflate(R.layout.child_item, null);
holder = new ViewHolder();
if (imageLoader == null)
imageLoader = AppController.getInstance().getImageLoader();
i = (NetworkImageView) convertView
.findViewById(R.id.flag);
i.setImageUrl(String.valueOf(child.get(childPosition).getImage()), imageLoader);
convertView.setTag(holder);
System.out.println("position" + checkedPositions.get(groupPosition));
if (checkedPositions.get(groupPosition) != null) {
boolean isChecked = checkedPositions.get(groupPosition).get(childPosition);
i.setBackgroundResource(R.color.bg);
if(!isChecked){
}
} else {
System.out.println("false");
}
} else {
holder = (ViewHolder) convertView.getTag();
}
holder.text = (TextView) convertView.findViewById(R.id.label);
holder.text.setText(child.get(position).getName());
return convertView;
}
static class ViewHolder {
TextView text;
}
}
In My Assumption
ExpandListAdapter Class
In getChildView() method childPosition does not depends on what country flag is being clicked , Because childPosition here returns the position of the Grid view, not the flags under it
So, no need to pass childPosition in constructor of GridView ,since childPosition will always return 1
To get actual flag clicked position Use onClickListener inside your GridAdapter like:
#Override
public View getView(int position, View convertView, ViewGroup parent) {
ViewHolder holder = null;
NetworkImageView i;
childPosition = position;
if (convertView == null) {
} else {
holder = (ViewHolder) convertView.getTag();
}
convertView.setOnclickListener(new OnClickListener{
#Override
onClick(View v){
isChecked=child.get(childPosition).isChecked();
if(!isChecked){
child.get(childPosition).setChecked(true);
}
else {
child.get(childPosition).setChecked(false);
}
});
No need to handle checked positions separately create two methods in your child class isChecked() and setChecked() to maintain check-uncheck state of flags.
Change color of selected or checked flag here
holder.text = (TextView) convertView.findViewById(R.id.label);
holder.text.setText(child.get(position).getName());
return convertView;
}
and remove your Check logic from ExpandListAdapter Class :
gridView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
setClicked(groupPosition, childPosition);
System.out.println("position" + checkedPositions.get(groupPosition));
if (checkedPositions.get(groupPosition) != null) {
boolean isChecked = checkedPositions.get(groupPosition).get(childPosition);
if(!isChecked){
}
} else {
System.out.println("false");
}
}
});
You need to set an 'OnItemClickListener' to your gridAdapter, and overide the onItemClick method as following.
Note :- This will highlight the ImageView you click and if you happened to click another ImageView in the same GridView, that ImageView also will be highlighted! Like in a 'multiple selection'.
gridAdapter.setOnItemClickListener(new AdapterView.OnItemClickListener() {
#Override
public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
ImageView selectedFlagImageView = (ImageView) view;
selectedFlagImageView.setBackgroundColor(Color.parseColor("#37a93400"));
}
});
This will color the background of the selected ImageView. Color code I've used in here is simply, more alpha and less RGBs.(I used Android Studio color chooser)
Following images will give you an idea about how it will look when giving a background color like this.
Without background color :
With background color :