Search code examples
androidandroid-imageviewandroid-radiogroupandroid-radiobutton

Merge the radio button and imageviews programmatically


I want to show the images with radio buttons and show this with radio group as user would be able to choose the option by reading the text and viewing the image. How can I make this possible?

Here is the code by which radio buttons are created and also image view dynamically, but these are created in radio group when I click the radio button to choose it shows error as image view can not be cast to radio button and this makes the image view as a child in radio group also and it is not working but showing perfect.

public RadioGroup showNationalCan(RadioGroup rg,Context context,ImageView iv,String voterNA){

    //candidate address  as punjab kpk etc

    if(conn==null){

    }
    try{
        RadioButton rb;
        Statement st=conn.createStatement();
        ResultSet rs=st.executeQuery("select * from AM_NATIONAL where ca_na=N'"+voterNA+"'");
        while (rs.next()) {
            rb=new RadioButton(context);
            rb.setTextColor(Color.BLACK);
            rb.setId(rs.getInt(1));
            rb.setText(rs.getString(2)+"\n"+rs.getString(3)+"\n");

            iv=new ImageView(context);
            byte[] photo=rs.getBytes(4);
            Bitmap bitmap;
            bitmap=BitmapFactory.decodeByteArray(photo, 0, photo.length);
            iv.setImageBitmap(bitmap);
            iv.setEnabled(false);


            rg.addView(iv);
            rg.addView(rb);
        }
        rs.close();
        st.close();

    } catch (SQLException e){
        e.printStackTrace();
    }
    return rg;
}

Solution

  • Here is my own answer which is working now absolutely perfect. I answered it here because others would be able to do that and able to set images direct from the external database like SQL also.

    rg.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
    
                @Override
                public void onCheckedChanged(RadioGroup group, int checkedId) {
                    // TODO Auto-generated method stub
                    for(int i=0; i<rg.getChildCount();i++)
                    {
                        RadioButton rbtn=(RadioButton)rg.getChildAt(i+1);
                        if(rbtn.getId()==checkedId)
                        {
                            serial=rbtn.getId();
                            flag=true;
                            return;
                        }
                        else
                        {
                            rbtn.setChecked(false);
                        }
                    }
    
                }
            });
    

    The issue was there that radio group have image view in it as child and this would not be clicked as radio buttons. I just increment the i with i+1 as it will get the radio button every time.