I am new to android development. I want to create RadioButton group programmetically in java class and set the text to the individual radio buttons.
Please Help on this
Thanks in Advance.
This program block shows how to create RadioButton group programmatically.
Hope it will help you.
public class RadioGroupActivity extends Activity {
protected static final String TAG = "RadioGroupActivity";
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.radiogroup);
RadioGroup radGrp = (RadioGroup)findViewById(R.id.radGrp);
int checkedRadioButtonID = radGrp.getCheckedRadioButtonId();
radGrp.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup arg0, int id) {
switch(id) {
case -1:
Log.v(TAG, "Choices cleared!");
break;
case R.id.chRBtn:
Log.v(TAG, "Chose Chicken");
break;
case R.id.fishRBtn:
Log.v(TAG, "Chose Fish");
break;
case R.id.stkRBtn:
Log.v(TAG, "Chose Steak");
break;
default:
Log.v(TAG, "Huh?");
break;
}
}});
}
}
You have good example here:
Creating RadioButtons programmatically
or this example also good:
Programmatically-added RadioButtons refuse to obey LayoutParams weighting
Here you have it...
ln = (LinearLayout)findViewById(R.id.Linear_layout); // Assuming linearLayout is your parent layout
RadioGroup rg = new RadioGroup(context); // create the RadioGroup
rg.setLayoutParams(new LinearLayout.LayoutParams(
LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT, 1f));
cg_Value = new String{“item 1”, “item 2”, “item 3”};
rb = new RadioButton[cg_Value.length];
rg.setOrientation(RadioGroup.HORIZONTAL);// horizontal or vertical depends on requirement
for (int l = 0; l < cg_Value.length; l++) {
rb[l] = new RadioButton(context);
rg.addView(rb[l]); // the RadioButtons are added to
// the radioGroup instead of the
// layout
rb[l].setTextColor(Color.BLACK);
rb[l].setText(cg_Value[l]);
rb[l].setTextSize(14);
}
//rb[1].setChecked(true);
ln.addView(rg);
Hope this helps
Related
I have some code that generates in the activity some radiobuttons:
public void drawRAnswers(int pst){
int drawables = qmclist.get(pst).getAnswers().size();
RadioGroup l1 = new RadioGroup(this);
l1.setOrientation(LinearLayout.VERTICAL);
for (int i=0;i<drawables;i++){
RadioButton rd = new RadioButton(this);
rd.setId(i);
rd.setText(current.getAnswers().get(i).getAns());
l1.addView(rd);
}
parentLinearLayout.addView(l1, parentLinearLayout.getChildCount());
}
What I want to do is be able to verify which ones (radiobuttons) are checked when I click a button:
public void onAddAnswer(View v){
position++;
delete();
drawRAnswers(position);
}
For now, what this button does is only load the next set of radiobuttons in the view and delete the current ones, but I don't check which ones are selected. Do you know how I could do this in this onAddAnswer method? I would like to put the text of each selected radiobutton in a list.
Thanks.
I managed to figure this one out myself. Here is what I have done:
public class Activity extends AppCompatActivity {
RadioGroup currentGroup;
...
public void onAddAnswer(View v){
if (currentGroup.getCheckedRadioButtonId()==-1){
Toast.makeText(getApplicationContext(), "Veuillez sélectionner au moins une réponse",
Toast.LENGTH_LONG).show();
} else {
int selectedId = currentGroup.getCheckedRadioButtonId();
RadioButton selectedRadio = (RadioButton)findViewById(selectedId);
Toast.makeText(getApplicationContext(), selectedRadio.getText().toString()+" is selected",
Toast.LENGTH_SHORT).show();
position++;
delete();
updateData(position);
}
}
...
public void drawRAnswers(int pst){
int drawables = qmclist.get(pst).getAnswers().size();
RadioGroup l1 = new RadioGroup(this);
currentGroup = l1;
l1.setOrientation(LinearLayout.VERTICAL);
for (int i=0;i<drawables;i++){
RadioButton rd = new RadioButton(this);
rd.setId(i);
rd.setText(current.getAnswers().get(i).getAns());
l1.addView(rd);
}
parentLinearLayout.addView(l1, parentLinearLayout.getChildCount());
}
}
So basically what I am doing is have a RadioGroup for every time I draw radiobuttons, match it with the currentGroup and check if I have (or not) any radiobuttons selected. If yes, then I find out which one.
Sometimes when i want to select choices in radio buttons there is something wrong with radio buttons which i can select Two radios However sometimes is right as default way it must be worked.
Here two sample in my application :
Here's my Code :
span.replace(0,0,getText(R.string.ForeSingleChoice));
new DynamicViews().makeNormalContent(getApplicationContext(),span,linearLayout,16,16,16,16,16.0f);
span.clear();
radioGroup = new DynamicViews().makeRadioGroup(getApplicationContext(),linearLayout);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop1_2),-1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop2_2),5);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop3_2),-1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop4_2),-1);
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
switch (checkedId)
{
case 5: goToNextLevel= true ;
break;
default: goToNextLevel = false;
break;
}
}
});
DynamicViews makeRadioButton:
public RadioButton makeRadioButton(Context context, RadioGroup radioGroup, String text, int Id) {
RadioButton radioButton = new RadioButton(context);
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
radioButton.setBackgroundResource(R.drawable.backgroundbetweenradios);
radioButton.setLayoutParams(Params);
radioButton.setPadding(dpToPx(8,context) , dpToPx(8,context) , dpToPx(8,context) , dpToPx(8,context));
radioButton.setId(Id);
radioButton.setText(text);
radioButton.setTextColor(Color.BLACK);
radioGroup.addView(radioButton);
return radioButton;
}
DynamicViews makeRadioGroup:
public RadioGroup makeRadioGroup(Context context, LinearLayout linearLayout) {
RadioGroup radioGroup = new RadioGroup(context);
LinearLayout.LayoutParams Params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT);
radioGroup.setLayoutParams(Params);
radioGroup.setOrientation(LinearLayout.VERTICAL);
CardView cardView = new CardView(context);
cardView.setCardBackgroundColor(Color.WHITE);
cardView.setCardElevation(8.0f);
Params.setMargins(dpToPx(16,context) , dpToPx(16,context) , dpToPx(16,context) , dpToPx(16,context));
cardView.setLayoutParams(Params);
cardView.addView(radioGroup);
linearLayout.addView(cardView);
return radioGroup;
}
My application is consists of a lot of radiobuttons ,This is the approach i've made these radio buttons , what's the problem ? is this a bug ?
Have you tried to give each radio button unique id?
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop1_2),1);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop2_2),5);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop3_2),2);
new DynamicViews().makeRadioButton(getApplicationContext(),radioGroup,getString(R.string.Choice_Q2Mathematicsop4_2),3);
add this on your onCreate()
CompoundButton.OnCheckedChangeListener listener = new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
if(isChecked){
rbtn1.setChecked(yesrbtn == buttonView);
rbtn2.setChecked(norbtn == buttonView);
....
}
}
};
rbtn1.setOnCheckedChangeListener(listener);
rbtn2.setOnCheckedChangeListener(listener);
what this does is making sure that radiobuttons are not allowed to have 2 or more selection
In my application I am adding RadioButton dynamically depending on requirement.
Below is the code :
RadioGroup rg = new RadioGroup(StartExamActivity.this);
View v = new View(StartExamActivity.this);
v.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, 2));
v.setBackgroundColor(Color.parseColor("#3593D4"));
rg.setLayoutParams(new RadioGroup.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
rg.setOrientation(LinearLayout.VERTICAL);
for (int i = 0; i < list.size(); i++) {
rdbtn[i] = new RadioButton(StartExamActivity.this);
rdbtn[i].setLayoutParams(new RadioGroup.LayoutParams(RadioGroup.LayoutParams.MATCH_PARENT, RadioGroup.LayoutParams.WRAP_CONTENT, 1f));
rdbtn[i].setId(i);
rdbtn[i].setText(list.get(i));
final String value = rdbtn[i].getText().toString();
rdbtn[i].setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (value.equalsIgnoreCase(answer)) {
marks = marks + 2;
}
}
});
rg.addView(rdbtn[i]);
}
questionContainer.addView(rg);
Now I want to increase the value of marks by 2 only ones even when RadioButton is checked multiple times. For that I want to know whether RadioButton is checked or not.
How to do this??
Please Help!!
Simple thing,
Why don't you use OnClickListener instead of onCheckedChanged>
rdbtn[i].setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean isChecked) {
if(isChecked) {
// Write your logic here...
}
});
I am looking for something similar in android where I can add radiobuttons to each cells in Table and get their position. Does anyone has worked on it before, if you can share the sample code would be helpful. Thanks
The following pseudocode should get you started:
//create a radio group
RadioGroup rg = new RadioGroup(context);
RadioGroup.LayoutParams rgParams = new RadioGroup.LayoutParams(
RadioGroup.LayoutParams.WRAP_CONTENT,
RadioGroup.LayoutParams.WRAP_CONTENT);
rg.setLayoutParams(rgParams);
//add the radio group to the row.
rowView.addView(rg);
//add radio buttons
for (i = 0; i < length; i++) {
RadioButton btn = new RadioButton(context);
btn.setText(description[i]);
//or save an object which will hold all information you need
btn.setTag(rowNumber);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
Log.d(TAG, v.getTag());
}
});
if (<some condition>) {
btn.setChecked(true);
}
rg.addView(btn);
}
hi i am doing one application here i need to disply 6 images in 3 colunmns and 3 rows.and then when i click each image i need to perform different onclick action.i teried some way using arraylist with forloop.using below code i applied onclick function into all images but here 2 cloumn 3 images onclick function working but i first column 3 images not working onclick function.but i need to apply different onclick action to each button. so please any one help me how to apply onclick action to array of images.
game2 .class:
public class game2 extends Activity implements OnClickListener {
TableLayout layout;
int i=0;
int f=0;
Integer[] images={R.drawable.abig,R.drawable.cbig,R.drawable.dbig,R.drawable.abig,R.drawable.cbig,R.drawable.dbig};
List<Integer> solutionList = Arrays.asList(images);
Integer[] randomNumbers,randomNumbers1;
TableLayout.LayoutParams param,param1;
ImageView[] plus=new ImageView[6];
TableRow[] row = new TableRow[6];
RelativeLayout.LayoutParams lp2,lp1,lp3,lp4,lp5;
RelativeLayout linear;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main1);
layout = new TableLayout (this);
layout.setLayoutParams( new TableLayout.LayoutParams(40,50) );
param=new TableLayout.LayoutParams(TableLayout.LayoutParams.WRAP_CONTENT,TableLayout.LayoutParams.WRAP_CONTENT);
param.setMargins(25, 0, 0, 0);
lp1=new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.WRAP_CONTENT,RelativeLayout.LayoutParams.WRAP_CONTENT);
linear=(RelativeLayout)findViewById(R.id.linear);
Collections.shuffle(solutionList);
randomNumbers = (Integer[])solutionList.toArray();
int unique=0;
for (f=0; f<3; f++) {
row[f] = new TableRow(this);
for (int c=0; c<2; c++) {
plus[f]=new ImageView(this);
plus[f].setBackgroundResource(randomNumbers[unique]);
plus[f].setOnClickListener(this);
row[f].addView(plus[f], 200,100);
unique++;
} // for
layout.addView(row[f],param);
} // for
linear.addView(layout,lp1);
setContentView(linear);
}
public void onClick(View view) {
if(view==plus[0])
{
Toast.makeText(game2.this, "view", Toast.LENGTH_SHORT).show();
}
if(view==plus[1])
{
Toast.makeText(game2.this, "view1", Toast.LENGTH_SHORT).show();
}
if(view==plus[2])
{
Toast.makeText(game2.this, "view2", Toast.LENGTH_SHORT).show();
}
if(view==plus[3])
{
Toast.makeText(game2.this, "view3", Toast.LENGTH_SHORT).show();
}
if(view==plus[4])
{
Toast.makeText(game2.this, "view4", Toast.LENGTH_SHORT).show();
}
if(view==plus[5])
{
Toast.makeText(game2.this, "view5", Toast.LENGTH_SHORT).show();
}
}
}
Can this may be problem for (int c=0; c<2; c++)? use for (int c=0; c<3; c++) .. c<3 for 3 columns.. And let me know what happen..
EDIT:
Also
ImageView[] plus=new ImageView[9];
int unique=0;
for (f=0; f<3; f++) {
row[f] = new TableRow(this);
for (int c=0; c<3; c++) {
plus[unique]=new ImageView(this);
plus[unique].setBackgroundResource(randomNumbers[unique]);
plus[unique].setOnClickListener(this);
plus[unique].setId(unique);
row[f].addView(plus[unique], 200,100);
unique++;
}
And in onClick()
public void onClick(View view) {
switch(view.getId()){
case 0:
{
Toast.makeText(game2.this, "view", Toast.LENGTH_SHORT).show();
}
.
.
.
case 8:
{
Toast.makeText(game2.this, "view8", Toast.LENGTH_SHORT).show();
}
}
}
Use ArrayList instead of array.. Right now you are not adding all the elements.. In nested for loop your elemnts are getting replaced... So use ArrayList... And I don't see a need for such a complex code, You keep UI in XML and still can achieve the Same.. The present code is hard to understand and even you cannot after some days.. You cannot maintain this code..
Use plus[unique] in place of plus[f] in all 3 lines of below loop
for (int c=0; c<2; c++) {
... }
simple set ID to every imageView when creating ImageView. then setOnClickListener().
onClick(View v) {
switch(v.getId()) {
case 1st_ImageViewID:
break;
case 2nd_ImageView_ID:
break;
case 3rd_ImageView_ID:
break;
}
}