【发布时间】:2018-10-28 21:00:16
【问题描述】:
我试图弄清楚如何在 android 上获取所选动态创建的单选按钮的文本。我被卡住了,需要在 stackoverflow 社区寻求帮助。
我也想当我只按下按钮时它会烤文本。
希望有人能指出正确的方向。
谢谢
MainActivity.java
public class MainActivity extends AppCompatActivity implements View.OnClickListener{
Button btnPress1,btnPress2;
String names[] = {"Braces Adjustment","Tooth Extraction","Cleaning"};
RadioButton r1;
@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
btnPress1 = (Button) findViewById(R.id.btnPress1);
btnPress2 = (Button) findViewById(R.id.btnPress2);
LinearLayout l = (LinearLayout) findViewById(R.id.linearLayout);
RadioGroup r = new RadioGroup(this);
r.setOrientation(RadioGroup.VERTICAL);
RadioGroup.LayoutParams rl;
//This is where i generate a dynamic radio button
for(int i=0; i<names.length;i++){
r1= new RadioButton(this);
r1.setId(i + 1);
r1.setText(names[i]);
r1.setButtonDrawable(R.drawable.custom_radio_button);
r1.setPadding(10,10,10,10);
r1.setGravity(Gravity.CENTER_VERTICAL);
rl=new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT,RadioGroup.LayoutParams.MATCH_PARENT);
rl.setMargins(10,15,0,0);
r.addView(r1,rl);
}
l.addView(r);
}
@Override
public void onClick(View view) {
switch (view.getId()){
case R.id.btnPress1:
//Toast here the text of radio button i selected but when i press the button
Toast.makeText(MainActivity.this,"BUTTON1",Toast.LENGTH_SHORT).show();
break;
case R.id.btnPress2:
//Toast here the text of radio button i selected but when i press the button
Toast.makeText(MainActivity.this,"BUTTON2",Toast.LENGTH_SHORT).show();
break;
}
}
【问题讨论】:
标签: java android radio-button