2015-06-21 21 views
0

我正在嘗試檢索選中的單選按鈕ID,以便我可以隨後執行切換並根據用戶檢查的內容發生某些操作,然後按下「完整調查「按鈕。然而,下面的方法檢索一些奇怪的ID(不是我爲XML文件中的那個單選按鈕指定的ID,它給了我一個像「[email protected]」這樣的大名字。)Android Studio:從activity_main.xml中檢索單選按鈕ID

@Override 
protected void onCreate(Bundle savedInstanceState) { 
    super.onCreate(savedInstanceState); 
    setContentView(R.layout.activity_main); 

    //set up our textview 
    showChoiceTextView = (TextView)findViewById(R.id.showTextView); 
    radioGroup = (RadioGroup)findViewById(R.id.radioGroupID); 
    showButton = (Button)findViewById(R.id.showChoiceButton); 


    showButton.setOnClickListener(new View.OnClickListener() { 
     @Override 
     public void onClick(View v) { 


      int selectedOption = radioGroup.getCheckedRadioButtonId(); 
      radioChoiceButton = (RadioButton)findViewById(selectedOption); 
      String text = radioChoiceButton.toString(); 
      Toast.makeText(getApplicationContext(),text,Toast.LENGTH_LONG).show(); 
     } 
    }); 
+0

您必須使用[getText()](http://developer.android.com/reference/android/widget/RadioButton.html)方法(從TextView繼承)來獲取RadioButton的值。現在您正在打印對象的表示形式。 –

+0

我試過了,但它返回了我在單選按鈕上寫的文本,但沒有分配給它的ID。 – WerdaFerk

+0

我真的很抱歉,我的壞。像@ dor00012說,你可以使用[getId()](http://developer.android.com/reference/android/view/View.html#getId())方法。在這裏看到一個使用它的例子[點擊事件響應](http://developer.android.com/guide/topics/ui/controls/radiobutton.html#HandlingEvents) –

回答

0

爲了得到一個視圖的,你必須使用view.getText()方法的文本。 記住一個radioGroup中是一個對象,文本是它的價值觀之一。

此外,檢索它的ID,你必須使用的getId( )方法

你想要檢索的id是常量的名稱,getId()檢索它的值如果我說例如:

int id = 10; 

然後10是它的值(使用的getId()來檢索) 和 「ID」 是它的名字。

+0

當我使用getId()時,它提供了一個9個字符的單選按鈕選擇整數,但不是我分配給它的ID。 – WerdaFerk

+0

明白了,謝謝!我意識到我的原代碼做了一些我仍然不懂的東西, int selectedOption = radioGroup.getCheckedRadioButtonId(); < - 這是給我10位數字ID的。所以我在上面Eric的鏈接中使用了這個例子。 – WerdaFerk