【问题标题】:Setting text of a radio button dynamically in Android在Android中动态设置单选按钮的文本
【发布时间】:2014-04-19 10:51:27
【问题描述】:

我是 android 新手,正在使用 mysql 在 android 中开发一个测验应用程序项目。我想动态设置单选按钮的文本。如何访问单选组的各个单选按钮,以在 .java 文件中设置每个单选按钮的文本?请帮助我解决这个问题。提前致谢。

【问题讨论】:

  • 使用 rb.setText("text");

标签: android adt


【解决方案1】:
RadioGroup mGroup = (RadioGroup) findViewById(R.id.radioGroup1);
int count = mGroup.getChildCount();
for(int i = 0;i<count;i++){
    if(mGroup.getChildAt(i) instanceof RadioButton)
        ((RadioButton) mGroup.getChildAt(i)).setText("Radio Button "+i);
}

我希望这会对你有所帮助。让我知道发生了什么。

【讨论】:

    【解决方案2】:

    在你的 xml 文件中创建单选按钮。在应用的 mainActivity 中获取单选按钮。

    RadioButton rb1 = (RadioButton) findViewById(R.id.radioButton1);
    

    使用以下方法更改与按钮关联的文本

    rb1.setText("new text");
    
    this is how a xml of radio group looks like
     <RadioGroup
            android:id="@+id/radioGroup1"
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:layout_alignLeft="@+id/radioButton2"
            android:layout_below="@+id/radioButton2"
            android:layout_marginTop="58dp" >
    
            <RadioButton
                android:id="@+id/radio0"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:checked="true"
                android:text="RadioButton" />
    
            <RadioButton
                android:id="@+id/radio1"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="RadioButton" />
    
            <RadioButton
                android:id="@+id/radio2"
                android:layout_width="wrap_content"
                android:layout_height="wrap_content"
                android:text="RadioButton" />
        </RadioGroup>
    
    to access each radio button of a group you can use its name
    example radio0,radio1,radio2 are the three radio buttons in a radio group
    you can access it by 
    RadioButton rb0 = (RadioButton) findViewById(R.id.radio0);
    rb0.setText("new text");
    

    【讨论】:

    • 如何访问单个单选按钮?
    • 这是在 xml 中创建无线电组的方式
    猜你喜欢
    • 1970-01-01
    • 2018-10-28
    • 1970-01-01
    • 1970-01-01
    • 2021-11-13
    • 2015-03-13
    • 2014-01-27
    • 2019-03-25
    • 1970-01-01
    相关资源
    最近更新 更多