java - 获取Android中RadioGroup的索引

标签 java android radio-group

我在 RadioGroup 中有两个 RadioButton:

<RadioGroup
    android:id="@+id/rgTripType"
    android:layout_width="wrap_content"
    android:layout_height="wrap_content"
    android:layout_weight="4" >

    <RadioButton
        android:id="@+id/rbOneWay"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:checked="true"
        android:text="One Way" />

    <RadioButton
        android:id="@+id/rbRound"
        android:layout_width="wrap_content"
        android:layout_height="wrap_content"
        android:text="Round" />
</RadioGroup>

我在 Java 文件中将 RadioGroup 称为:

    final RadioGroup rgTypeOfTrip = (RadioGroup) findViewById(R.id.rgTripType);

        btnCalc.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                  Toast.makeText(MainActivity.this, CALL FUNCTION GETINDEX() to get value, Toast.LENGTH_SHORT).show();
        });

        rgTypeOfTrip.setOnCheckedChangeListener(new OnCheckedChangeListener() {
            @Override
            public void onCheckedChanged(RadioGroup group, int checkedId) {
                // TODO Auto-generated method stub

                // Method 1
                int pos=rgTypeOfTrip.indexOfChild(findViewById(checkedId));
                    getIndex(pos);
                Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();
            }
        });

public int getIndex(int k) {
    return k;
}

它应该做的是显示一个Toast,其中包含单选按钮组中单选按钮的索引。相反,它会导致我的程序崩溃。知道如何解决吗?

更新:索引问题已解决。

问题:如何在 btnClick 函数中使用索引值 (POS)?

最佳答案

它崩溃是因为 pos 是一个整数变化。如果你传递一个 int 值作为第二个参数,你会要求 android 寻找一个 id 为你提供的 int 的字符串。如果不存在,将抛出 ResourcesNotFoundException

Toast.makeText(MainActivity.this, pos, Toast.LENGTH_SHORT).show();

 Toast.makeText(MainActivity.this, String.valueOf(pos), Toast.LENGTH_SHORT).show();

关于java - 获取Android中RadioGroup的索引,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17837435/

相关文章:

android - 循环通过 Radiogroup 以对 Radiobutton 标签执行操作

java - Android 开发和 TDD

java - 线程中的异常 "main"org.springframework.context.ApplicationContextException : Unable to start embedded container;

java - 代码行未初始化导致空指针执行

java - 如何解决 glassfish 上的 Web 服务应用程序中的 "HTTP Status 500 - Internal Server Error"问题?

android - 在 Android 中以编程方式添加到 RadioGroup 时,RadioButtons 具有不同的样式

android - 适用于 Android 的应用内计费支持国家

android - FirebaseRemoteConfig fetchAndActivate 不更新新值

java - 视频持续时间设置不正确 (exoplayer2)