简体   繁体   English

Android Studio:从activity_main.xml检索单选按钮ID

[英]Android Studio: Retrieve radio button id from activity_main.xml

I am trying to retrieve the checked radio button ID so that I can then do a Switch and have something happen depending on what the user has checked, followed by them pressing the "complete survey" button. 我试图检索选中的单选按钮ID,以便随后可以进行切换,并根据用户检查的内容进行某些操作,然后按“完成调查”按钮。 However, the method below retrieves some odd ID (not one that I've specified for that radio button in the XML file. It gives me a large name like "android.widget.RadioButton@5363daa0." What gives? 但是,下面的方法检索一些奇数ID(不是我为XML文件中的单选按钮指定的一个ID。它为我提供了一个大名称,例如“ android.widget.RadioButton@5363daa0。”这是什么意思?

@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();
        }
    });

To get a view's text you must use view.getText() method. 要获取视图的文本,必须使用view.getText()方法。 Remember the a radioGroup is an object and the text is one of it's values. 请记住,radioGroup是一个对象,文本是它的值之一。

Also, to retrieve it's id you must use getId() method. 另外,要检索其ID,必须使用getId()方法。

The id you want to retrieve is the name of the constant, and getId() retrieves it's value. 您要检索的id是常量的名称,而getId()检索其值。 If i say for example: 如果我说例如:

int id = 10;

Then 10 is it's value (use getId() to retrieve) and "id" is it's name. 然后10是它的值(使用getId()进行检索),而“ id”是它的名称。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM