【问题标题】:How to set the CardView as the background for radio button dynamically from java code in android?如何从android中的java代码动态地将CardView设置为单选按钮的背景?
【发布时间】:2016-10-24 19:26:46
【问题描述】:

我需要将 CardView 作为我动态创建的 android 中单选按钮的背景。我已经为单选组编写了 xml,我正在创建单选按钮并动态添加它们。现在我需要为单选按钮添加背景,这将是卡片视图。那么我该怎么做呢?我可以使用在背景中添加一个图标 appCompatRadioButton1.setBackgroundResource(R.drawable.csr_icon);

我知道我们可以创建自定义模板并添加到此单选按钮的背景中,但背景文件必须在可绘制文件夹中,而它是具有卡片视图的布局文件。

【问题讨论】:

  • AFAIK,你不能。但是,理论上,您可以 get a Bitmap of the CardView 并将其设置为 RadioButton 的背景。
  • 好的。所以没有办法实现这样的设计?
  • 我相信没有。
  • 好的。让我们看看我能为它做些什么。谢谢你帮助我。 :)

标签: android android-cardview android-radiogroup android-radiobutton


【解决方案1】:

您可以拥有一个带有 FrameLayout 的 CardView,然后将 RadioGroup 作为子项添加到 CardView 中的 FrameLayout。

我只需要将 RadioGroup 的 xml 设置为 CardView,其中包含带有 ID 的 RadioGroup,而不是经历这些麻烦。然后访问广播组只是在 CardView 上使用 findViewById

假设您使用的是 SDK 20 及更高版本,请使用它。通过 findViewById 加载单选按钮。这不是专门的 cardView 而是模拟 CardView 背景

单个单选按钮文件

<?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

临时drawable如下

<?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>

【讨论】:

  • 是的。我们可以做到,但是如果我编写这种代码,那么所有单选按钮都将在同一个卡片视图中,而我想为每个单选按钮提供单独的卡片视图
猜你喜欢
  • 1970-01-01
  • 2016-05-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多