gpt4 book ai didi

java - 获取Android中RadioGroup的索引

转载 作者:行者123 更新时间:2023-12-01 18:45:51 25 4
gpt4 key购买 nike

我在 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/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com