0

I need to put the CardView as background for radio button in android which i am creating dynamically. I have written xml for radio group and i am creating radio button and adding them dynamically. Now i need to put the background for the radio button which will be card view. So how can i do that? I can add an icon in background by using appCompatRadioButton1.setBackgroundResource(R.drawable.csr_icon);

And i know we can create custom template and add to the background of this radio button but the background file must be in drawable folder while it is layout file which is having card view.

Shravan Jain
  • 43
  • 1
  • 1
  • 7

1 Answers1

0

You can have a CardView with a FrameLayout and then add the RadioGroup as a child to the FrameLayout in the CardView.

Instead of going through the hassle I would just have the xml for the RadioGroup be a CardView which contains the RadioGroup in there with an id. Accessing the radio group then is just using findViewById on the CardView

Assuming you are working with SDK 20 and above use this. Load the radio button by findViewById. This is not specifically a cardView but simulates a CardView background

Individual Radio Button File

<?xml version="1.0" encoding="utf-8"?>
<FrameLayout xmlns:android="http://schemas.android.com/apk/res/android"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:padding="16dp"
    android:elevation="2dp"
    android:background="@drawable/temp">

    <RadioButton
        android:id="@+id/radioButton"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="This is a temp string for radio"/>

</FrameLayout

The temp drawable is as follows

<?xml version="1.0" encoding="utf-8"?>
<shape xmlns:android="http://schemas.android.com/apk/res/android"
    android:shape="rectangle">
    <solid android:color="@android:color/white" />
    <corners android:radius="8dp" />
</shape>
prats110892
  • 6,599
  • 1
  • 12
  • 6
  • Yes. We can do it but if i write this kind of code then all of the radio buttons will be in same cardview while i want to give the separate cardview for each radio button – Shravan Jain Oct 24 '16 at 19:57