How to select one radio button from dynamically created radio buttons? - android

I have a situation to select one radio button from dynamically created radio buttons. I know it is possible with Radio group but still I am not able to do it because my situation is little different. Let me explain it.
I have a question like "A recent survey found that in British secondary schools" with 4 options like
A.
B.
C.
D.
All data coming from the server in json form. I have created the view dynamically with one question and four options with radio buttons. But what i am understanding is every row is new row and I am not able to select only one radio buttons from all radio buttons. Every button is selecting individually but I want to select only one radio button on which I click.
Any help would be appreciated.
you can see my view below:
My code is :
LinearLayout linearLayoutForQuestions = (LinearLayout) view.findViewById(R.id.questionsLinearLayout);
linearLayoutForQuestions.removeAllViews();
//set the questions for the user
for (int ss = 0; ss < totalNoOfQuestions.size(); ss++) {
final List<String> list = new ArrayList();
list.add("SELECT");
TextView textView = new TextView(activity);
textView.setTextSize(15);
textView.setTextColor(view.getResources().getColor(R.color.black));
textView.setTypeface(typeface1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 20, 0, 0);
textView.setLayoutParams(params);
String question = totalNoOfQuestions.get(ss).getQuestions();
String questionNo = totalNoOfQuestions.get(ss).QuestionNo;
textView.setText("Question " + questionNo + " " + question);
//linearlayout and set data inside it
LinearLayout parent = new LinearLayout(activity);
parent.removeAllViews();
parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.VERTICAL);
int optionSize = totalNoOfQuestions.get(ss).getOptions().size();
for (int s = 0; s < optionSize; s++) {
//children of parent linearlayout
LinearLayout layout2 = new LinearLayout(activity);
layout2.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
layout2.setOrientation(LinearLayout.HORIZONTAL);
layout2.setGravity(Gravity.CENTER);
String optionNo = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOptionNo();
TextView textView1 = new TextView(activity);
textView1.setText(optionNo);
textView.setTextSize(15);
final RadioButton radioButton = new RadioButton(activity.getApplicationContext());
radioButton.setId(s);
radioButton.setBackgroundResource(R.drawable.settings_background_ripple);
LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
pa.setMargins(10,10,10,10);
radioButton.setLayoutParams(pa);
radioButton.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
int checkedRadioButtonId = buttonView.getId();
Toast.makeText(activity, "hit it", Toast.LENGTH_SHORT).show();
}
});
String questionOption = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOption();
TextView textView2 = new TextView(activity);
textView2.setTextSize(15);
textView2.setText(questionOption);
layout2.addView(textView1);
layout2.addView(radioButton);
layout2.addView(textView2);
parent.addView(layout2);
}
linearLayoutForQuestions.addView(textView);
linearLayoutForQuestions.addView(parent);
}

I have been working on it from a while and finally I find the way how to do it , posting my answer to let others take idea from it. I make it work by taking the array of Textview and Radiogroup outside the inner for loop.
Thank you everyone for the assistance. Happy Coding:)
LinearLayout linearLayoutForQuestions = (LinearLayout) view.findViewById(R.id.questionsLinearLayout);
linearLayoutForQuestions.removeAllViews();
totalNoOfQuestions = readingTests[countReadingTest].getQuestion();
//set the questions for the user
for (int ss = 0; ss < totalNoOfQuestions.size(); ss++) {
groupNo = ss;
final List<String> list = new ArrayList();
list.add("SELECT");
TextView textView = new TextView(activity);
textView.setTextSize(15);
textView.setTextColor(view.getResources().getColor(R.color.black));
textView.setTypeface(typeface1);
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
params.setMargins(0, 20, 0, 0);
textView.setLayoutParams(params);
String question = totalNoOfQuestions.get(ss).getQuestions();
String questionNum = totalNoOfQuestions.get(ss).QuestionNo;
textView.setText("Question " + questionNum + " " + question);
//linearlayout and set data inside it
LinearLayout parent = new LinearLayout(activity);
parent.removeAllViews();
parent.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT));
parent.setOrientation(LinearLayout.VERTICAL);
final int optionSize = totalNoOfQuestions.get(ss).getOptions().size();
final RadioButton[] radioButton = new RadioButton[optionSize];
int size = totalNoOfQuestions.size();
final RadioGroup[] radioGroup = new RadioGroup[size]; //you can also create in xml
radioGroup[ss] = new RadioGroup(activity);
radioGroup[ss].setId(ss + 100);
radioGroup[ss].setOrientation(RadioGroup.VERTICAL)ΓΈ;
//this textview is for the optionsNo like A,B,C,D
final TextView[] textView1 = new TextView[optionSize];
LinearLayout layoutOptionsNo = new LinearLayout(activity);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(ViewGroup.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.MATCH_PARENT);
layoutOptionsNo.setOrientation(LinearLayout.VERTICAL);
layoutOptionsNo.setWeightSum(optionSize);
layoutOptionsNo.setGravity(Gravity.CENTER);
layoutOptionsNo.setPadding(10, 0, 0, 0);
layoutOptionsNo.setLayoutParams(layoutParams);
LinearLayout layoutOptions = new LinearLayout(activity);
layoutOptions.setLayoutParams(new LinearLayout.LayoutParams(ViewGroup.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT, 1.0f));
layoutOptions.setOrientation(LinearLayout.HORIZONTAL);
layoutOptions.setWeightSum(4);
layoutOptions.setGravity(Gravity.CENTER);
//inner loop for the options for every single question
for (int s = 0; s < optionSize; s++) {
String optionNo = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOptionNo();
textView1[s] = new TextView(activity);
textView1[s].setText(optionNo);
textView1[s].setTextSize(15);
textView1[s].setGravity(Gravity.CENTER);
LinearLayout.LayoutParams pa = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT));
pa.setMargins(10, 10, 10, 10);
pa.weight = 1;
textView1[s].setLayoutParams(pa);
String questionOption = totalNoOfQuestions.get(ss).getOptions().get(s).getQuestionOption();
radioButton[s] = new RadioButton(activity);
radioButton[s].setId(s);
radioButton[s].setText(questionOption);
radioButton[s].setTextSize(15);
radioButton[s].setPadding(2, 2, 2, 2);
radioButton[s].setBackgroundResource(R.drawable.settings_background_ripple);
LinearLayout.LayoutParams pa2 = new LinearLayout.LayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT, 1.0f));
pa2.setMargins(10, 10, 10, 10);
pa2.weight = 1;
radioGroup[ss].setLayoutParams(pa2);
radioGroup[ss].addView(radioButton[s]);
layoutOptionsNo.addView(textView1[s]);
}
radioGroup[ss].setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
int originalId ;
int id = group.getId();{
originalId = id-100;
}
questionNo = totalNoOfQuestions.get(originalId).getQuestionNo();
optionNo = totalNoOfQuestions.get(0).getOptions().get(checkedId).getQuestionOptionNo();
}
});
layoutOptions.addView(layoutOptionsNo);
layoutOptions.addView(radioGroup[ss]);
parent.addView(layoutOptions);
linearLayoutForQuestions.addView(textView);
linearLayoutForQuestions.addView(parent);
}
boolean showOptionHint = totalNoOfQuestions.get(0).OptionList;
LinearLayout linearLayoutForOptions = (LinearLayout) view.findViewById(R.id.optionsLinearLayout);
linearLayoutForOptions.removeAllViews();
if (showOptionHint == true) {
//dynamic creation of options under the quesiton layout
List<ReadingTest.QuestionBean.OptionsBean> questionOptions = readingTests[countReadingTest].getQuestion().get(0).getOptions();
for (int ss = 0; ss < questionOptions.size(); ss++) {
String options = questionOptions.get(ss).getQuestionOption();
String optionsNo = questionOptions.get(ss).getQuestionOptionNo();
TextView textView = new TextView(activity);
textView.setTextSize(18);
textView.setTypeface(typeface);
textView.setTextColor(view.getResources().getColor(R.color.black));
textView.setText(optionsNo + ". " + options);
linearLayoutForOptions.addView(textView);
}
}

Use RadioGroup as below:
LinearLayout layout = (LinearLayout) findViewById(R.id.layout); //layout defined in xml main activity layout
RadioGroup radioGroup = new RadioGroup(this); //you can also create in xml
LinearLayout.LayoutParams p = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.FILL_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT
);
layout.addView(radioGroup, p);
/*radio button 1*/
RadioButton radioButtonView1 = new RadioButton(this);
radioButtonView1.setText("RadioButton1");
radioButtonView1.setOnClickListener(this);
radioGroup.addView(radioButtonView1, p);
/*radio button 2*/
RadioButton radioButtonView2 = new RadioButton(this);
radioButtonView2.setText("RadioButton2");
radioButtonView2.setOnClickListener(mThisButtonListener);
radioGroup.addView(radioButtonView2, p);
/*radio button 3*/
RadioButton radioButtonView3 = new RadioButton(this);
radioButtonView3.setText("RadioButton3");
radioButtonView3.setOnClickListener(mThisButtonListener);
radioGroup.addView(radioButtonView3 , p);
/*radio button 4*/
RadioButton radioButtonView4 = new RadioButton(this);
radioButtonView4 .setText("RadioButton4");
radioButtonView4.setOnClickListener(mThisButtonListener);
radioGroup.addView(radioButtonView4 , p);
Here you can select only one option out of multiple
As you required how to select value, then please use following code snippet:
radioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId)
{
radioButton = (RadioButton) findViewById(checkedId);
Toast.makeText(getBaseContext(), radioButton.getText(), Toast.LENGTH_SHORT).show(); //text related to option selected.
}
}
);
Thanks

Hello #Sandeep Singh Bandral
You have done a great Work, Why you are doing such a heavy work
Just Create a Radio Group Work and assign a Id ,and call setOnCheckedChangeListener
You can see here
radioGroup.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// find which radio button is selected
if(checkedId == R.id.answer1) {
Toast.makeText(getApplicationContext(), "Answer1",
Toast.LENGTH_SHORT).show();
} else if(checkedId == R.id.answer2) {
Toast.makeText(getApplicationContext(), "Answer2",
Toast.LENGTH_SHORT).show();
}else if(checkedId == R.id.answer3) {
Toast.makeText(getApplicationContext(), "Answer3",
Toast.LENGTH_SHORT).show();
} else {
Toast.makeText(getApplicationContext(), "Answer4",
Toast.LENGTH_SHORT).show();
}
}
});
In the place of Toast ,DO YOUR STUFF
Test Case:if you don't know how many radio buttons for each Question, you can see the below code over here
radiogroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
void onCheckedChanged(RadioGroup radioGroup, int checkedId) {
for(int i=0; i<radioGroup.getChildCount(); i++) {
RadioButton btn = (RadioButton) radioGroup.getChildAt(i);
if(btn.getId() == checkedId) {
String text = btn.getText();
// do something with text
return;
}
}
}
});

I know this is rather old, but I just had the same problem. The solution is to change the state of RadioButton after adding it to RadioGroup by addView(). I guess this is also what BAKUS tried to say by his sample code.
copied from here

Related

Android Creating Views Programmatically not getting separated instances

I got the following code
for (int i = 0; i < cantcuenta ; i++) {
textview = new ArrayList<>();
final Integer nro = i + 1;
Hmayor = new LinearLayout(view.getContext());
LinearLayout.LayoutParams param = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.MATCH_PARENT);
param.weight = pesoLayout;
Hmayor.setOrientation(LinearLayout.VERTICAL);
Hmayor.setWeightSum(1);
Hmayor.setLayoutParams(param);
scrollview = new ScrollView(view.getContext());
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
params.weight = 0.65f;
scrollview.setLayoutParams(params);
linearinterno = new LinearLayout(view.getContext());
linearinterno.setLayoutParams(new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, LinearLayout.LayoutParams.WRAP_CONTENT));
linearinterno.setOrientation(LinearLayout.VERTICAL);
scrollview.addView(linearinterno);
for (int j = 0; j < 10; j++)
{
test = new TextView(view.getContext());
test.setId(j);
test.setText("Lorem Ipsum" + j);
test.setVisibility(View.GONE);
textview.add(test);
}
boleta = new Button(view.getContext());
RelativeLayout.LayoutParams parambo = new RelativeLayout.LayoutParams(100, 50);
boleta.setLayoutParams(parambo);
boleta.setText("BOLETA");
boleta.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
boleta.setTypeface(Typeface.DEFAULT_BOLD);
boleta.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
boleta.setTextColor(getResources().getColor(white, null));
boleta.setBackgroundColor(getResources().getColor(colorAccent, null));
boleta.setId(nro);
boleta.setPadding(0,0,0,0);
boleta.setVisibility(View.GONE);
boleta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
factura = new Button(view.getContext());
RelativeLayout.LayoutParams paramfa = new RelativeLayout.LayoutParams(100, 50);
paramfa.addRule(RelativeLayout.RIGHT_OF, boleta.getId());
factura.setLayoutParams(paramfa);
factura.setText("FACTURA");
factura.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
factura.setTypeface(Typeface.DEFAULT_BOLD);
factura.setTextAlignment(View.TEXT_ALIGNMENT_CENTER);
factura.setTextColor(getResources().getColor(white, null));
factura.setBackgroundColor(getResources().getColor(colorAccent, null));
factura.setPadding(0,0,0,0);
factura.setVisibility(View.GONE);
factura.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
}
});
ncuenta = new Button(view.getContext());
LinearLayout.LayoutParams paramb = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT, 0);
paramb.weight = 0.15f;
ncuenta.setLayoutParams(paramb);
ncuenta.setPadding(0,0,0,0);
ncuenta.setText("CUENTA " + nro);
ncuenta.setTextSize(TypedValue.COMPLEX_UNIT_SP, 10);
ncuenta.setTypeface(Typeface.DEFAULT_BOLD);
ncuenta.setTextAlignment(View.TEXT_ALIGNMENT_TEXT_START);
ncuenta.setTextColor(getResources().getColor(letras, null));
ncuenta.setBackgroundColor(getResources().getColor(transparent, null));
ncuenta.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v)
{
Boolean sw = false;
for (TextView este : textview)
{
if (este.getVisibility() == View.GONE)
{
este.setVisibility(View.VISIBLE);
linearinterno.addView(este);
factura.setVisibility(View.VISIBLE);
boleta.setVisibility(View.VISIBLE);
sw = true;
}
}
if (!sw)
{
for (TextView este : textview)
{
este.setVisibility(View.GONE);
factura.setVisibility(View.GONE);
boleta.setVisibility(View.GONE);
}
linearinterno.removeAllViews();
}
}
});
Hmayor.addView(ncuenta);
Hmayor.addView(scrollview);
linearinternodw = new LinearLayout(view.getContext());
LinearLayout.LayoutParams paramdw = new LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,0);
paramdw.weight = 0.2f;
linearinternodw.setLayoutParams(paramdw);
Hmayor.addView(linearinternodw);
relainterno = new RelativeLayout(view.getContext());
RelativeLayout.LayoutParams paramr = new RelativeLayout.LayoutParams(RelativeLayout.LayoutParams.MATCH_PARENT, RelativeLayout.LayoutParams.MATCH_PARENT);
relainterno.setLayoutParams(paramr);
relainterno.addView(factura);
relainterno.addView(boleta);
linearinternodw.addView(relainterno);
theParent.addView(Hmayor);
}
it creates this distribution
when i press the button "CUENTA 1" with the name "ncuenta" in the code it should make all the text in the its own layout gone along with the buttons "BOLETA" and "FACTURA" also shown in the picture but instead, it makes it gone for the "CUENTA 2" views, I have done this kind of coding for recyclerviews and everything get instanced separatedly, would think that with a FOR everytime it does create a new instance of any view it would get attached to the corresponding cycle of the FOR.
if I divide the screen in 4 the first 3 buttons will show and hide the "CUENTA 4" wich tells me the the setOnclickListener its only taking the last set of items instanced..
Any ideas on how could solve this?
thanks in advance
Your onClickListener executes this code
for (TextView este : textview)
{
if (este.getVisibility() == View.GONE)
{
este.setVisibility(View.VISIBLE);
linearinterno.addView(este);
factura.setVisibility(View.VISIBLE);
boleta.setVisibility(View.VISIBLE);
sw = true;
}
}
When executed, the contents of the textview ArrayList will be the elements you add in the last iteration, that's why only the views in the last section are targeted.
Hope it helps.

Not able to add view dynamically

I have linear layout R.id.linearLayoutQuantityPrice in XML.
I want to add a new linear layout inside that dynamically.
The new linear layout has two textviews and one imageview.
List<Price> priceList = database.getItemQuantityPrice(id);
LinearLayout linearLayoutQuantityPrice = (LinearLayout) rowView
.findViewById(R.id.linearLayoutQuantityPrice);
for (int i=0; i<priceList.size() ; i++) {
Price price = new Price();
price = priceList.get(i);
LinearLayout newLinearLayout = new LinearLayout(context);
newLinearLayout.setOrientation(LinearLayout.HORIZONTAL);
LayoutParams newLayoutParams = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
newLinearLayout.setPadding(2, 2, 2, 2);
newLinearLayout.setWeightSum(3);
int iqpId = price.getIqpId();
String quantityIn = price.getQuantityIn();
int quantity = price.getItmQnt();
int itemPrice = price.getItmPrc();
TextView tvQuantity=new TextView(context);
tvQuantity.setId(price.getIqpId()+10);
tvQuantity.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1.0f));
tvQuantity.setTextSize(12);
if(quantityIn.equalsIgnoreCase("gm") && quantity>=1000){
quantity = quantity/1000;
quantityIn = new String("KG");
}
tvQuantity.setText(""+quantity+" "+quantityIn);
newLinearLayout.addView(tvQuantity);
TextView tvPrice=new TextView(context);
tvPrice.setId(price.getIqpId()+11);
tvPrice.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT,1.0f));
tvPrice.setTextSize(12);
tvPrice.setText("Rs. "+itemPrice);
newLinearLayout.addView(tvPrice);
ImageView ivButton = new ImageView(context);
ivButton.setId(iqpId);
ivButton.setLayoutParams(new LinearLayout.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.MATCH_PARENT, 1.0f));
ivButton.setImageDrawable(rowView.getResources().getDrawable(R.drawable.add_button));
ivButton.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
int toCartId = v.getId();
Toast.makeText(context, "Added to cart" + toCartId, Toast.LENGTH_SHORT).show();
}
});
linearLayoutQuantityPrice.addView(newLinearLayout);
}
The code doesn't get any errors. But the desired views are not added.
Because you forgot to set the layout params.
newLinearLayout.setLayoutParams(newLayoutParams)
Try to use this. This is worked for me.
ArrayList<Component> components;
LinearLayout llRowContainer;
llRowContainer = (LinearLayout) findViewById(R.id.ll_row_container);
components = IappApp.getContext().getDBManager()
.getComponentList(COMPONENT_TYPE, ACTIVITY_TYPE);
int index = 0;
for (Component component : components) {
View rowView = View.inflate(this, R.layout.dae_general_info_row , null);
llRowContainer.addView(rowView);
final TextView txtViewTitle = (TextView) rowView
.findViewById(R.id.txtViewTitle);
final EditText editTextAns = (EditText) rowView
.findViewById(R.id.editTextAns);
editTextAns.setHint(component.getUnit()+"");
txtViewTitle.setText(++index + ". " + component.getTitle());
editTextAns.setTag(component);
}

Pass value from radio button to database

I made a layout which contains radio button. I want to pass value of selected radio button to database so how can I get this value.?
Code is given below..Please help me..
private View drawRadioTypeQuestion(Question question, ArrayList<QuestionOption> questionOptions) {
LinearLayout layout = new LinearLayout(this);
layout.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
layout.setOrientation(LinearLayout.VERTICAL);
layout.setPadding(5, 5, 5, 5);
TextView tv = new TextView(this);
tv.setText(question.Question_Order + ". " + question.Question_Title);
tv.setTextSize(16);
// tv.setTypeface(PhoneStatus.getRobotoMediumTypeface(this));
layout.addView(tv);
RadioGroup rg = new RadioGroup(this);
rg.setOrientation(RadioGroup.VERTICAL);
for (QuestionOption opt : questionOptions) {
RadioButton rb = new RadioButton(this);
rb.setText(opt.Question_Answer_Value);
rb.setTextSize(16);
rg.addView(rb);
}
layout.addView(rg);
PhoneStatus.overrideFonts(QuestionListActivity.this, layout);
tv.setTypeface(PhoneStatus.getRobotoMediumTypeface(this));
return layout;
}
try this code
rg.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(RadioGroup group, int checkedId) {
// TODO Auto-generated method stub
RadioButton rb = (RadioButton) findViewById(checkedId);
String value = rb.getText().toString();
}
});
Implement click listener on radio button. On onclick event add value of selected radio button to database..
Visit Here for official document
http://developer.android.com/guide/topics/ui/controls/radiobutton.html
and
http://android-er.blogspot.in/2009/11/radiogroup-and-radiobutton.html

table row selection error in scrollview

i am creating a table layout with radio group by dynamically adding radiobuttons to it and i want to know which row is selected containing the radio group and i want to retrive the texview data also in the same row .how can i do that any suggestion will be a great help for me.
public class TabActivity extends Activity {
TableLayout table;
RadioGroup mRadioGroup;
ArrayList<String> list_name;
int color_blue = -16776961;
int color_gray = -7829368;
int color_black = -16777216;
int color_white = -1;
final int CHECK_BUTTON_ID = 982301;
int ids_check[];
boolean bool_check[];
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
table = (TableLayout) findViewById(R.id.tableLayout1);
list_name = new ArrayList<String>();
list_name.add("Close");
list_name.add("Cristiano");
list_name.add("David");
list_name.add("Fernando");
list_name.add("Messi");
list_name.add("Kaka");
list_name.add("Wayne");
list_name.add("use");
list_name.add("e");
list_name.add("eff");
list_name.add("euyr");
list_name.add("ejjyytuty");
list_name.add("madre");
list_name.add("yuir");
list_name.add("eyrty");
list_name.add("etytr");
list_name.add("ewrrtt");
bool_check = new boolean[list_name.size()];
ids_check = new int[list_name.size()];
createTableRows();
}
public void createTableRows()
{
for (int i = 0; i < list_name.size(); i++)
{
final TableRow table_row = new TableRow(this);
TextView tv_name = new TextView(this);
Button btn_check = new Button(this);
ImageView img_line = new ImageView(this);
table_row.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, LayoutParams.FILL_PARENT));
table_row.setBackgroundColor(color_black);
table_row.setGravity(Gravity.CENTER_HORIZONTAL);
// table_row.setFocusable(true);
mRadioGroup = new RadioGroup(this);
// test adding a radio button programmatically
final RadioButton[] mbutton=new RadioButton[7];
for(int l=0;l<7;l++){
mbutton[l]=new RadioButton(this);
mbutton[l].setText("test"+l);
mRadioGroup.addView(mbutton[l]);
}
// LinearLayout.LayoutParams layoutParams = new RadioGroup.LayoutParams(
// RadioGroup.LayoutParams.WRAP_CONTENT,
// RadioGroup.LayoutParams.WRAP_CONTENT);
// mRadioGroup.addView(newRadioButton);
tv_name.setText((CharSequence) list_name.get(i));
tv_name.setTextColor(color_blue);
tv_name.setTextSize(30);
tv_name.setTypeface(Typeface.DEFAULT_BOLD);
tv_name.setWidth(150);
btn_check.setLayoutParams(new LayoutParams(30, 30));
btn_check.setBackgroundResource(R.drawable.small_checkbox_unchecked);
img_line.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT, 2));
img_line.setBackgroundResource(R.drawable.separater_line);
table_row.addView(tv_name);
table_row.addView(btn_check);
table_row.addView(mRadioGroup);
table.addView(table_row);
table.addView(img_line);
//table.addView(mRadioGroup);
mRadioGroup.setOnCheckedChangeListener(new RadioGroup.OnCheckedChangeListener() {
public void onCheckedChanged(RadioGroup mRadioGroup, int checkedId) {
for(int i=0; i<mRadioGroup.getChildCount(); i++) {
RadioButton btn = (RadioButton) mRadioGroup.getChildAt(i);
int t=table.indexOfChild(table_row);
System.out.println(t);
if(btn.getId() == checkedId) {
String text = btn.getText().toString();
// do something with text
Log.d(text," event1");
return;
}
}
}
});
}
}
}
Why are you not using ListView ? there's nothing in the code that cannot be done by a list view?
You can add you layout by setting the custom adapter.

How to add a button dynamically in Android?

How to add a button dynamically in Android?
Button myButton = new Button(this);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
Have a look to this example
try this:
for (int i = 1; i <= 20; i++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
Button btn = new Button(this);
btn.setId(i);
final int id_ = btn.getId();
btn.setText("button " + id_);
btn.setBackgroundColor(Color.rgb(70, 80, 90));
linear.addView(btn, params);
btn1 = ((Button) findViewById(id_));
btn1.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(view.getContext(),
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
Try this:
LinearLayout ll = (LinearLayout)findViewById(R.id.layout);
Button btn = new Button(this);
btn.setText("Manual Add");
btn.setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT));
ll.addView(btn);
for (int k = 1; k < 100; k++) {
TableRow row = new TableRow(this);
innerloop:
for (int l = 1; l < 4; l++) {
btn = new Button(this);
TableRow.LayoutParams tr = new TableRow.LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
layout.setWeightSum(12.0f);
tr.weight = 0;
btn.setLayoutParams(tr);
btn.setTextColor(a);
btn.setHeight(150);
btn.setWidth(150);
btn.setId(idb);
btn.setText("Button " + idb);
row.addView(btn);
}
}
try this
private void createLayoutDynamically(int n) {
for (int i = 0; i < n; i++) {
Button myButton = new Button(this);
myButton.setText("Button :"+i);
myButton.setId(i);
final int id_ = myButton.getId();
LinearLayout layout = (LinearLayout) findViewById(R.id.myDynamicLayout);
layout.addView(myButton);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
}
Try this code
Button btn=new Button(this);
btn.setId(btn);
btn.setBackgroundResource(R.drawable.image);
btn.setMinimumHeight(150);
btn.setMinimumWidth(150);
Relativelayout.addView(btn);
Check this up.
LinearLayout ll_Main = new LinearLayout(getActivity());
LinearLayout ll_Row01 = new LinearLayout(getActivity());
LinearLayout ll_Row02 = new LinearLayout(getActivity());
ll_Main.setOrientation(LinearLayout.VERTICAL);
ll_Row01.setOrientation(LinearLayout.HORIZONTAL);
ll_Row02.setOrientation(LinearLayout.HORIZONTAL);
final Button button01 = new Button(getActivity());
final Button button02 = new Button(getActivity());
final Button button03 = new Button(getActivity());
final Button button04 = new Button(getActivity());
ll_Row01.addView(button01);
ll_Row01.addView(button02);
ll_Row02.addView(button03);
ll_Row02.addView(button04);
ll_Main.addView(ll_Row01);
ll_Main.addView(ll_Row02);
button04.setVisibility(View.INVISIBLE);
button04.setVisibility(View.VISIBLE);
Button btn = new Button(this);
btn.setText("Submit");
LinearLayout linearLayout = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams buttonlayout = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
linearLayout.addView(btn, buttonlayout);
Try this code. It will work fine..
public class DynamicViewsActivity extends Activity {
Button button;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
//setContentView(R.layout.activity_dynamic_views);
ScrollView scrl=new ScrollView(this);
final LinearLayout ll=new LinearLayout(this);
ll.setOrientation(LinearLayout.HORIZONTAL);
LinearLayout.LayoutParams layoutParams = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT, LinearLayout.LayoutParams.WRAP_CONTENT);
layoutParams.setMargins(100, 500, 100, 200);
scrl.addView(ll);
Button add_btn=new Button(this);
add_btn.setText("Click Here");
ll.addView(add_btn, layoutParams);
final Context context = this;
add_btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent intent = new Intent(context, App2Activity.class);
startActivity(intent);
}
});
this.setContentView(scrl);
}
}
Try following code.
LinearLayout layout = (LinearLayout) findViewById(R.id.llayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText("Button1");
layout.add(btn);
btn = new Button(this);
btn.setText(Button2);
layout.add(btn);
like this you add Buttons as per your requirements.
public void add_btn() {
lin_btn.setWeightSum(3f);
for (int j = 0; j < 3; j++) {
LinearLayout.LayoutParams params1 = new LinearLayout.LayoutParams(
LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT);
params1.setMargins(10, 0, 0, 10);
params1.weight = 1.0f;
LinearLayout ll;
ll = new LinearLayout(this);
ll.setGravity(Gravity.CENTER_VERTICAL);
ll.setOrientation(LinearLayout.HORIZONTAL);
ll.setLayoutParams(params1);
final Button btn;
btn = new Button(DynamicActivity.this);
btn.setText("A"+(j+1));
btn.setTextSize(15);
btn.setId(j);
btn.setPadding(10, 8, 10, 10);
ll.addView(btn);
lin_btn.addView(ll);
btn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
if(v.getId()==0)
{
txt_text.setText("Hii");
}else if(v.getId()==1)
{
txt_text.setText("hello");
}else if(v.getId()==2)
{
txt_text.setText("how r u");
}
}
});
}
}
Actually I add to the xml layout file anything that could be used! Then from the source code of the specific Activity I get the object by its id and I "play" with the visibility method.
Here is an example:
((Spinner)findViewById(R.id.email_spinner)).setVisibility(View.GONE);
I've used this (or very similar) code to add several TextViews to a LinearLayout:
// Quick & dirty pre-made list of text labels...
String names[] = {"alpha", "beta", "gamma", "delta", "epsilon"};
int namesLength = 5;
// Create a LayoutParams...
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.FILL_PARENT);
// Get existing UI containers...
LinearLayout nameButtons = (LinearLayout) view.findViewById(R.id.name_buttons);
TextView label = (TextView) view.findViewById(R.id.master_label);
TextView tv;
for (int i = 0; i < namesLength; i++) {
// Grab the name for this "button"
final String name = names[i];
tv = new TextView(context);
tv.setText(name);
// TextViews CAN have OnClickListeners
tv.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
label.setText("Clicked button for " + name);
}
});
nameButtons.addView(tv, params);
}
The main difference between this and dicklaw795's code is it doesn't set() and re-get() the ID for each TextView--I found it unnecessary, although I may need it to later identify each button in a common handler routine (e.g. one called by onClick() for each TextView).
Button myButton = new Button(this);
myButton.setId(123);
myButton.setText("Push Me");
LinearLayout ll = (LinearLayout)findViewById(R.id.buttonlayout);
LayoutParams lp = new LayoutParams(LayoutParams.MATCH_PARENT, LayoutParams.WRAP_CONTENT);
ll.addView(myButton, lp);
myButton.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
Toast.makeText(DynamicLayout.this,
"Button clicked index = " + id_, Toast.LENGTH_SHORT)
.show();
}
});
If you want to add dynamically buttons try this:
public class MainActivity extends Activity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main2);
for (int i = 1; i <= 5; i++) {
LinearLayout layout = (LinearLayout) findViewById(R.id.myLinearLayout);
layout.setOrientation(LinearLayout.VERTICAL);
Button btn = new Button(this);
btn.setText(" ");
layout.addView(btn);
}
}
You could create a base layout for your button and dynamically change only what is specific, like this project I made to run different exercises from a Material Design course I'm taking:
In this example, I use a preconfigured AppCompatButton:
layout_base_button.xml
<android.support.v7.widget.AppCompatButton
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="#+id/btn_base"
android:layout_width="200dp"
android:layout_height="wrap_content"
android:layout_gravity="center"
android:layout_marginTop="8dp"
style="#style/RaisedButton"
>
</android.support.v7.widget.AppCompatButton>
<style name="RaisedButton" parent="Widget.AppCompat.Button.Colored">
<item name="android:textSize">11sp</item>
<item name="android:textStyle">bold</item>
</style>
And in the MainActivity I created some instances and changed what I need, like the button text and onClick event:
<ScrollView
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context="udemy.android.materialdesign.MainActivity">
<LinearLayout
android:id="#+id/base_layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical"
>
</LinearLayout>
</ScrollView>
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout baseLayout = findViewById(R.id.base_layout);
baseLayout.addView(createButton("TextFields", baseLayout,
view -> startActivity(createIntent(TextFieldsActivity.class))
));
baseLayout.addView(createButton("Buttons", baseLayout,
view -> startActivity(createIntent(ButtonsActivity.class))
));
baseLayout.addView(createButton("Toolbar", baseLayout,
view -> startActivity(createIntent(ToolbarActivity.class))
));
}
private View createButton(String text, LinearLayout baseLayout, View.OnClickListener onClickEvent) {
View inflated = LayoutInflater.from(this).inflate(R.layout.layout_base_button, baseLayout, false);
AppCompatButton btnBase = inflated.findViewById(R.id.btn_base);
btnBase.setText(text);
btnBase.setOnClickListener(onClickEvent);
return btnBase;
}
private Intent createIntent(Class<?> cls) {
return new Intent(this, cls);
}
}
Sorry for being late...
I needed to create buttons even more dynamically, not just in runtime but by pressing another button. So clicking this button will dynamically create more buttons under it. I recommend having a ScrollView on the activity or limit the number of clicks - so no buttons go offscreen.
activity_main.xml
<?xml version="1.0" encoding="utf-8"?>
<androidx.constraintlayout.widget.ConstraintLayout
xmlns:android="http://schemas.android.com/apk/res/android"
xmlns:app="http://schemas.android.com/apk/res-auto"
xmlns:tools="http://schemas.android.com/tools"
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:context=".MainActivity">
<ScrollView
android:layout_width="match_parent"
android:layout_height="match_parent"
tools:layout_editor_absoluteY="675dp">
<LinearLayout
android:id="#+id/layout"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:orientation="vertical">
<Button
android:id="#+id/newItemButton"
android:layout_width="match_parent"
android:layout_height="wrap_content"
android:text="Button1" />
</LinearLayout>
</ScrollView>
</androidx.constraintlayout.widget.ConstraintLayout>
MainActivity.java
public class MainActivity extends AppCompatActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
LinearLayout ll = (LinearLayout)findViewById(R.id.layout); //Screen layout
LinearLayout.LayoutParams params = new
LinearLayout.LayoutParams(LinearLayout.LayoutParams.MATCH_PARENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
final Button newItemButton = findViewById(R.id.newItemButton);
newItemButton.setText("Create new button");
newItemButton.setOnClickListener(new View.OnClickListener() {
int pressCount = 1; //Count how many times button was pressed
public void onClick(View v) {
newItemButton.setText("Button Clicked: "+pressCount);
createButton(pressCount, params, ll); //Click to create new button
pressCount++;
}
});
} //end of onCreate
public void createButton(int id, LinearLayout.LayoutParams inputParams, LinearLayout inputLL) {
Button outButton = new Button(this);
outButton.setId(id);
final int id_ = outButton.getId();
outButton.setText("Button " + id_);
inputLL.addView(outButton, inputParams);
}
}//end of AppCompatActivity
This will give you an activity with a button.
When you click on that button, you spawn a new button underneath it.
If you spawn so many that they do not fit on the screen, the scrollView will take care of that.
In mainactivity.xml write:
<Button
android:id="#+id/search"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:text="Search"
android:visibility="invisible"/>
In main.java write:
Button buttonSearch;
buttonSearch = (Button)findViewById(R.id.search);
buttonSearch.setVisibility(View.VISIBLE);

Categories

Resources