我试图通过
获取RadioButton的父ID(RadioGroup的id)RadioGroup rg = (RadioGroup) arg0.getParent();
但失败了。建设后
RadioGroup rg = (RadioGroup) findViewById(R.id.radiogr);
运作良好。如何在运行时获取父ID?
失败了这些日志:
12-26 17:11:05.205: E/AndroidRuntime(912): FATAL EXCEPTION: main
12-26 17:11:05.205: E/AndroidRuntime(912): java.lang.ClassCastException: android.widget.LinearLayout
12-26 17:11:05.205: E/AndroidRuntime(912): at com.letmedraw.shopcart.ShopCartActivity.onCheckedChanged(ShopCartActivity.java:96)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.RadioGroup.setCheckedId(RadioGroup.java:172)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.RadioGroup.access$600(RadioGroup.java:52)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.RadioGroup$CheckedStateTracker.onCheckedChanged(RadioGroup.java:342)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.CompoundButton.setChecked(CompoundButton.java:127)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.CompoundButton.toggle(CompoundButton.java:86)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.RadioButton.toggle(RadioButton.java:69)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.widget.CompoundButton.performClick(CompoundButton.java:98)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.view.View$PerformClick.run(View.java:8816)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.os.Handler.handleCallback(Handler.java:587)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.os.Handler.dispatchMessage(Handler.java:92)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.os.Looper.loop(Looper.java:123)
12-26 17:11:05.205: E/AndroidRuntime(912): at android.app.ActivityThread.main(ActivityThread.java:4627)
12-26 17:11:05.205: E/AndroidRuntime(912): at java.lang.reflect.Method.invokeNative(Native Method)
12-26 17:11:05.205: E/AndroidRuntime(912): at java.lang.reflect.Method.invoke(Method.java:521)
12-26 17:11:05.205: E/AndroidRuntime(912): at com.android.internal.os.ZygoteInit$MethodAndArgsCaller.run(ZygoteInit.java:868)
12-26 17:11:05.205: E/AndroidRuntime(912): at com.android.internal.os.ZygoteInit.main(ZygoteInit.java:626)
12-26 17:11:05.205: E/AndroidRuntime(912): at dalvik.system.NativeStart.main(Native Method)
答案 0 :(得分:10)
android中的所有视图(控件)都是View
类型,因此您可以使用getId()
来查找ID。
int parentId = ((View) arg0.getParent()).getId();
答案 1 :(得分:1)
因为getParent()不是RadioGroup值,也不是id。 getParent()返回ViewParent类型,而不是View。
ViewParent是界面,View是一个类。
答案 2 :(得分:0)
似乎arg0 parent是LinearLayout,而不是Radio组,你正在尝试将它转换为RadioGroup,这就是它抛出异常的原因。
答案 3 :(得分:0)
只是为了进一步阐明接受的答案,您可以获取任何视图的父ID(以整数形式),就像这样
int parentId = ((View) arg0.getParent()).getId();
现在您可以将ID与R.id
进行比较以执行操作。因为所有视图的ID均以整数格式保存在Android中的R file
中。
if (parentId == R.id.your_id) { //
// Do whatever you want
}