Search code examples
androidexpandablelistview

how to assign counter value to expandable list view button


I have expandable list view and each one of view has button. I need to set a tag to each of the button like button1(count 0), button1(count 1), button1(count 2)....... I tried incrementing count each time but it is setting some random counter value.

I am suspecting that I am doing counter++ in wrong place please some one suggest me where I can increment the counter value.

Universally assigning counter:

int counter = 0;

In getChildView() method

 @Override
public View getChildView(final int i, final int i1, boolean b, View view, ViewGroup viewGroup) {
   if (view == null) {
        holder = new ViewHolder();
        LayoutInflater parentInflater = (LayoutInflater) mctx.getSystemService(mctx.LAYOUT_INFLATER_SERVICE);
        view = parentInflater.inflate(R.layout.itemname_child_layout, null);
        holder.button = view.findViewById(R.id.childrecordbtn);
 } else {
        holder = (ViewHolder) view.getTag();
 }

 holder.button.setTag(counter);

 holder.button..setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
          int tag = view.getTag();
          Log.i("Tag Value = ",tag);
        }
 }
 counter++;
 return view;
}

Above code returning some random values after button click.

Output :

Button1 : "Tag Value : 24"
Button2 : "Tag Value : 25"
Button3 : "Tag Value : 113"

Solution

  • Take a look at the definitation of getChildView():

    getChildView(int groupPosition, int childPosition, boolean isLastChild, View convertView, ViewGroup parent)
    

    That means in your code, i is the groupPosition and i1 is the childPosition. You should only rely on these parameters to determine the content of each row rather than using an external counter.

    You can get an one-dimensional array index by the follow calculation:

    int sum = 0;
    for(int j = 0;j < i; j++)
    {
           sum += getChildrenCount(j);
    }
    final int arrayIndex = sum + i1;
    holder.button.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View view) {
                Log.i("Tag Value = ",arrayIndex);
            }
     }