简体   繁体   English

如何在 android studio 中动态更改单选按钮的名称?

[英]How to change name of Radio button dynamically in android studio?

I am dynamically creating radio buttons as per the count given in the edit text.我正在根据编辑文本中给出的计数动态创建单选按钮。 I want to edit the name of the radiobutton after it gets created dynamically in the app, like the user has the privilege to name the radio button in the app.我想在应用程序中动态创建单选按钮后编辑它的名称,就像用户有权在应用程序中命名单选按钮一样。 How should I do that android studio This is my code for creating dyanmic radiobuttons so far.我应该怎么做 android studio 这是我迄今为止创建动态单选按钮的代码。 Here in the code rbn.setText("Radiobutton"+i) names the radiobutton as Radiobutton1, Radiobutton2, etc. instead of that I want to change the name of that in the app dynamically and write the name of the radiobutton one by one, help would appreciated please!这里在代码 rbn.setText("Radiobutton"+i) 中将单选按钮命名为 Radiobutton1、Radiobutton2 等,而不是我想在应用程序中动态更改它的名称并一一写入单选按钮的名称,帮助将不胜感激!

package com.example.EZPoll;
import androidx.appcompat.app.AppCompatActivity;

import android.os.Bundle;
import android.view.View;
import android.widget.Button;
import android.widget.EditText;
import android.widget.RadioButton;
import android.widget.RadioGroup;

public class Public_create extends AppCompatActivity {
    EditText mEtNumOfRadioBtns;
    Button mBtnAdd;
    RadioGroup mRgAllButtons;
    String option_name;
    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_public_create);
        mEtNumOfRadioBtns = findViewById(R.id.et_no);
        mBtnAdd = (Button) findViewById(R.id.btn);
        mRgAllButtons = (RadioGroup)findViewById(R.id.radiogroup);
        mBtnAdd.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                int number=Integer.parseInt(mEtNumOfRadioBtns.getText().toString().trim());
                for (int i = 1; i <= number ; i++) {
                    RadioButton rbn = new RadioButton(Public_create.this);
                    rbn.setId(View.generateViewId());
                    rbn.setText("Radiobutton "+i);
                    mRgAllButtons.addView(rbn);
                }
            }
        });
    }
}```

The problem that you have now is that you can't reference the buttons created in the loop through user interaction.您现在遇到的问题是您无法通过用户交互引用在循环中创建的按钮。 I suggest creating a List<myData> which contains a RadioButton and an EditText , show them in a RecyclerView or ListView .我建议创建一个包含RadioButtonEditTextList<myData> ,将它们显示在RecyclerViewListView中。

Then the user can edit the name of the RadioButton throught the EditText one by one.然后用户可以通过EditText逐一编辑RadioButton的名称。

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

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