如何在android中通过id动态更改查找视图的值?

时间:2015-03-22 18:21:19

标签: android

我是android的基础学习者。我想从我的代码中实现的是:我想动态地改变for循环中无线电组的单选按钮的值。然后,抓取文本值,以便我可以比较,让我们说,如果值是"取出",我想要检查rb1。 这是广播组

<RadioGroup
        android:layout_marginTop="20dp"
        android:layout_width="fill_parent"
        android:layout_height="120dp"
        android:layout_alignBottom="@+id/add"
        android:layout_alignParentLeft="true"
        android:layout_alignParentStart="true"
        android:layout_marginBottom="20dp"
        android:id="@+id/rg1">

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Take Out"
            android:id="@+id/rb1"
            android:checked="true"
            android:onClick="selectSomething"
            />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Sit down"
            android:id="@+id/rb2"
            android:checked="false" />

        <RadioButton
            android:layout_width="wrap_content"
            android:layout_height="wrap_content"
            android:text="Delivery"
            android:id="@+id/rb3"
            android:checked="false" />
    </RadioGroup>

到目前为止我尝试了什么:

int count = rg1.getChildCount();

        //Make checked if the value is equal
        for(int i = 0; i < count;i++){
            String myshit = "rb"+i;

            int id = getResources().getIdentifier(myshit, "id", getPackageName());
            RadioButton RadioValue = (RadioButton) findViewById(id);

            String _RadioValue = RadioValue.getText().toString();



            Log.d("abc",_RadioValue);

        }

为了进行测试,我想打印出Log中的值,但它不会编译并抛出错误。我的代码中只有一半。有没有更好的方法来解决这个问题?需要你的专长。谢谢 !

1 个答案:

答案 0 :(得分:1)

你这样做是错误的。

所有RadioButtons都应指向常用功能 也就是说,所有这些都应该分配这个属性:

android:onClick="selectSomething"

在该方法中,执行以下操作:

public final void selectSomething(final View v)
{
    switch(v.getId())
    {
        case R.id.rb1:
        {
            String str = "Take out";
            System.out.println(str);
            break;
        }
        // all other cases
        // ...
    }
}