0

I am dynamically adding a layout according to a particular array size which varies each time, as follows :

    for(int i = 0; i < topps.size(); i++)
    {
        lr1 = new LinearLayout(Main.this);
        lr1.setOrientation(LinearLayout.VERTICAL);
        scrool.addView(lr1);

        final View child = getLayoutInflater().inflate(R.layout.tops_data, null);
        red   = (TextView)child.findViewById(R.id.topp_detail_red_txt);
        black = (TextView)child.findViewById(R.id.topp_detail_black_txt);

        use = (ImageButton)child.findViewById(R.id.imageButton2);
        use.setOnClickListener(new View.OnClickListener() 
        {   
        @Override
        public void onClick(View v) 
        {
               if(bgh == false)
           {
Toast.makeText(this, "btn1 is "+child.getId(), Toast.LENGTH_SHORT).show();
            use.setBackgroundResource(R.drawable.tick_unsel);
           }
           else if(bgh == true)
           {
Toast.makeText(this, "btn1 is "+child.getId(), Toast.LENGTH_SHORT).show();
                    use.setBackgroundResource(R.drawable.tick_select);
               }
        }
         });
         lr1.addView(child);
         child.setId(main_cnt);
         use.setId(main_cnt);

In the above code everything is working fine, the number of views are listed as per the array size and I am getting the button id for each view.

The button image is not changing according to the condition, but toast prints correctly. For example :

if I have 5 views, when I click on the button of 3rd view the toast appears correctly with the setId but the image gets changed only in the 5th view.

How to change the image correctly in each view?

Iulia Barbu
  • 1,522
  • 12
  • 25
Siva K
  • 4,968
  • 14
  • 82
  • 161

2 Answers2

1

should try ............

v.setImageResource(R.drawable.tick_select);

or

v.setBackgroundResource(R.drawable.tick_select);

instead of

use.setBackgroundResource(R.drawable.tick_select);
Dheeresh Singh
  • 15,643
  • 3
  • 38
  • 36
0

You need to create a new instance of your ImageButton on each iteration.

Replace : use = (ImageButton)child.findViewById(R.id.imageButton2);

By : ImageButton use = (ImageButton)child.findViewById(R.id.imageButton2);

Aurélien Guillard
  • 1,203
  • 8
  • 20