2011-12-26 69 views
1

我試着通過如何在Android上獲取父ID?

RadioGroup rg = (RadioGroup) arg0.getParent(); 

得到單選按鈕(RadioGroup中的ID)的父ID,但失敗了。以下建設

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

爲什麼會失敗? ClassCastException異常? – jcxavier 2011-12-26 17:01:20

+0

向問題添加失敗消息(異常消息)將有助於獲得最準確的答案。 – kosa 2011-12-26 17:01:30

+1

'arg0.getparent()。getClass()。getName()'yield? – 2011-12-26 17:18:25

回答

8

Android中的所有視圖(控件)都是View類型,因此您可以使用getId()來查找該ID。

int parentId = ((View) arg0.getParent()).getId(); 
0

因爲的getParent()不是RadioGroup中值,而不是一個id任一。 getParent()返回ViewParent類型,而不是View。

ViewParent是接口,View是一個類。

0

看來arg0父母是LinearLayout,而不是Radio組,你試圖將它轉換爲RadioGroup,這就是爲什麼它拋出異常。