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.
Related
I want get second dynamic button text from another dynamic button OnClickListener event:
Here is define some dynamic buutons:
LinearLayout lv=(LinearLayout)findViewById(R.id.lv);
for (int k = 1; k <= str[0].length(); k++) {
LinearLayout.LayoutParams params = new LinearLayout.LayoutParams(100, 100);
btnTopEn = new Button(this);
btnTopEn.setId(k);
final int id_ = btnTopEn.getId();
btnTopEn.setText(" ");
lv.addView(btnTopEn, params);
btnTopEn = ((Button) findViewById(id_));
final Button finalBtnT = btnTopEn;
btnTopEn.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
finalBtnT.setText("");
}
});
}
Now I want text of second button from OnClickListener Event:
TableLayout layout = (TableLayout)findViewById(R.id.TableL);
String stt="RZCEADHPTAUJTSFR";
int l=0;
for (int f=0; f<=1; f++) {
TableRow tr = new TableRow(this);
for (int c=0; c<=7; c++) {
btnCEn = new Button (this);
String ss=(String.valueOf(stt.charAt(l)));
btnCEn.setText(ss);;
final Button finalBtnB = btnCEn;
btnCEn.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
int m=2;
btnTopEn = ((Button) findViewById(m));
final Button finalBtnT = btnTopEn;
if (finalBtnT.getText().equals("")) {
String stGetText=finalBtnB.getText().toString();
finalBtnT.setText(stGetText);
break;
}
}
}
});
TableRow.LayoutParams lp = new TableRow.LayoutParams(100,100);
tr.addView(btnCEn, lp);
}
layout.addView(tr);
}
I wrote some code in OnClickListener event but none happen!
What is the value of str in the first loop ?
Also you are setting the text to a space .
btnTopEn.setText(" ");
And while checking you check for empty :
if (finalBtnT.getText().equals("")){
}
Try changing to
if (finalBtnT.getText().toString().trim().equals("")){
}
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
I am trying to get words from several EditTexts and display them using TextView without using any layout. But the program is force closed every-time I run it.
LOGCAT: java.lang.RuntimeException: Unable to instantiate activity
ComponentInfo{com.example.tablelayout/com.example.tablelayout.MainActivity}:
java.lang.NullPointerException
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
LinearLayout linearLayout = new LinearLayout(this);
ViewGroup.LayoutParams params = new ViewGroup.LayoutParams(FILL_PARENT, WRAP_CONTENT);
linearLayout.setLayoutParams(params);
linearLayout.setOrientation(VERTICAL);
int count = 10;
linearLayout.addView(tableLayout(count));
linearLayout.addView(submitButton());
setContentView(linearLayout);
}
private Button submitButton() {
Button button = new Button(this);
button.setHeight(WRAP_CONTENT);
button.setText("Submit");
button.setOnClickListener(submitListener);
return button;
}
TextView txt=new TextView(this);
// Access the value of the EditText
private View.OnClickListener submitListener = new View.OnClickListener() {
public void onClick(View view) {
StringBuilder stringBuilder = new StringBuilder();
for (EditText editText : editTextList) {
stringBuilder.append(editText.getText().toString());
}
txt.setText(stringBuilder.toString().trim());
}
};
// Using a TableLayout as it provides you with a neat ordering structure
private TableLayout tableLayout(int count) {
TableLayout tableLayout = new TableLayout(this);
tableLayout.setStretchAllColumns(true);
int noOfRows = count / 5;
for (int i = 0; i < noOfRows; i++) {
int rowId = 5 * i;
tableLayout.addView(createOneFullRow(rowId));
}
int individualCells = count % 5;
tableLayout.addView(createLeftOverCells(individualCells, count));
return tableLayout;
}
private TableRow createLeftOverCells(int individualCells, int count) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
int rowId = count - individualCells;
for (int i = 1; i <= individualCells; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private TableRow createOneFullRow(int rowId) {
TableRow tableRow = new TableRow(this);
tableRow.setPadding(0, 10, 0, 0);
for (int i = 1; i <= 5; i++) {
tableRow.addView(editText(String.valueOf(rowId + i)));
}
return tableRow;
}
private EditText editText(String hint) {
EditText editText = new EditText(this);
editText.setId(Integer.valueOf(hint));
editText.setHint(hint);
editTextList.add(editText);
return editText;
}
}
TextView txt=new TextView(this);
you can't declare and initialize a class member View at the same time, because the Context is not yet valid
change it to:
public class MainActivity extends Activity {
private List<EditText> editTextList = new ArrayList<EditText>();
private TextView txt;
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
txt = new TextView(this);
// other code
also I noticed that you are not adding this View to any of the containers that your provided to setContentView. The suggestion will fix the crash but you will not see the TextView's content
Exception shows problem is in your manifest file.
Your package name is manifest tag and your activity are in different locations.
So I am trying to make a simple quiz application and I want to make sure that the user answers all the question before continuing to the next activity. At start the button I have set is unavailable and I want to make it available ONLY if all the question have been answered. I cant figure out where and how to check if all the question have an answer.
public class Quiz extends Activity
{
Button buttHole;
String countryName[] = { "India", "Pakistan", "China", "Nepal", "Pichmaala", "Blah" };
#Override
protected void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button)findViewById(R.id.button1);
buttHole.setEnabled(false);
//Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
for (int i = 1; i <= 3; i++)
{
//create text button
TextView title = new TextView(this);
title.setText("Question Number:" + i);
title.setTextColor(Color.GREEN);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[countryName.length];
RadioGroup radGr = new RadioGroup(this);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(l)
for (int j = 0; j < countryName.length; j++)
{
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(countryName[j]);
}
mLinearLayout.addView(radGr);
}
}
}
give radiobuttons id's as well and when you are going to submit this form(for example) mean on button click , get radio button object by id and then check radiobutton.isChecked().
Try following code to check whether user has given answer to all question or not
First Solution
int count = mLinearLayout.getChildCount();
for(int i=1;i<count ;i+=2){
RadioGroup rg = (RadioGroup) mLinearLayout.getChildAt(i);
if(rg.getCheckedRadioButtonId()==-1){
//Answer is not selected
//Do something to prevent execution
break;
}
}
Second Solution
public class Quiz extends Activity {
Button buttHole;
String countryName[] = { "India", "Pakistan", "China", "Nepal",
"Pichmaala", "Blah" };
ArrayList<RadioGroup> arrGroup;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_quiz);
buttHole = (Button) findViewById(R.id.button1);
buttHole.setEnabled(false);
// Creating the list of Questions
LinearLayout mLinearLayout = (LinearLayout) findViewById(R.id.linear1);
arrGroup = new ArrayList<RadioGroup>();
for (int i = 1; i <= 3; i++) {
// create text button
TextView title = new TextView(this);
title.setText("Question Number:" + i);
title.setTextColor(Color.GREEN);
mLinearLayout.addView(title);
// create radio button
final RadioButton[] rb = new RadioButton[countryName.length];
RadioGroup radGr = new RadioGroup(this);
// take a reference of RadioGroup view
arrGroup.add(radGr);
radGr.setOrientation(RadioGroup.VERTICAL);
radGr.setOnClickListener(l);
for (int j = 0; j < countryName.length; j++) {
rb[j] = new RadioButton(this);
radGr.addView(rb[j]);
rb[j].setText(countryName[j]);
}
mLinearLayout.addView(radGr);
}
}
public boolean checkQuestionsAnswer() {
int count = arrGroup.size();
for (int i = 0; i < count; i++) {
if (arrGroup.get(i).getCheckedRadioButtonId() == -1) {
//Return false, answer is remaining to given
//You can pass here position also to know question number
return false;
}
}
//Return true if all answer are given
return true;
}
}
I'm adding a checkbox in my application dynamically, and I want to delete the records which are checked. But, I'm not getting the ID of the checkbox. How can I do this?
Code:
package com.my.StudentInfoManagement;
public class ListData extends Activity{
DataHelper dh;
TableLayout tb;
CheckBox[] ch=new CheckBox[50];
EditText ed;
int a[]=new int[50];
int k=0;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.listdataxml);
dh=new DataHelper(this);
System.out.println("in list data");
List<String> names= this.dh.selectAll();
ed=(EditText) findViewById(R.id.ed_id);
tb=(TableLayout) findViewById(R.id.table);
int i,j=1;
TextView name1 = null,id,dob,gender,branch,email,address,mobile;
String name11,id1 = null,dob1,gender1,branch1,email1,address1,mobile1;
TableRow tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
TextView tv=new TextView(this);
String c = null;
String data[]=new String[50];
int cnt=0;
for(String name:names)
{
if((!name.equals("-999")))
{
data[cnt]=name;
cnt++;
System.out.println("........."+name);
}
else
{
cnt=0;
name1=new TextView(this);
name1.setText(data[1]+" ");
id=new TextView(this);
id.setText(data[0]+" ");
System.out.println("ID is...."+data[0]);
dob=new TextView(this);
dob.setText(data[3]+" ");
gender=new TextView(this);
gender.setText(data[2]+" ");
branch=new TextView(this);
branch.setText(data[4]+" ");
mobile=new TextView(this);
mobile.setText(data[5]+" ");
email=new TextView(this);
email.setText(data[6]+" ");
address=new TextView(this);
address.setText(data[7]+" ");
tr=new TableRow(this);
tr.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.WRAP_CONTENT));
ch[k]=new CheckBox(this);
System.out.println("sysout");
i=Integer.parseInt(data[0]);
ch[k].setId(i);
tr.addView(ch[k]);
a[k++]=i;
tr.addView(id);
tr.addView(name1);
tr.addView(dob);
tr.addView(gender);
tr.addView(branch);
tr.addView(mobile);
tr.addView(email);
tr.addView(address);
tb.addView(tr,new TableLayout.LayoutParams( LayoutParams.FILL_PARENT,LayoutParams.WRAP_CONTENT));
j++;
System.out.println("count"+j);
}
}
}
public void delete(View v){
System.out.println("In delete");
int bb=k,id ;
for (int i=0; i <k; i++)
{
final int j = a[i];
System.out.println("in for loop"+j);
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
System.out.println("00000000000000000..."+id);
dh.deleteData(id);
}
}
strong textJust take a global variable
int chkId = 1001;
then at time of adding CheckBox dynamically, set its id as
ch.setId(++chkId);
then at time of deleting CheckBox, you can get id of Checked CheckBox simple by using
getId()
methhod
See Following Demo:
public class ChkBoxesActivity extends Activity {
int chId = 1000;
int chPos = -1;
LinearLayout ll;
String[] names = {"Tom", "Dick", "Keanu", "Harry", "Katrina", "Peter", "Julia", "Emma"};
CheckBox[] ch;
/** Called when the activity is first created. */
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
ll = (LinearLayout) findViewById(R.id.ll);
ch = new CheckBox[names.length];
for(int i=0; i<names.length; i++) {
ch[i] = new CheckBox(this);
ch[i].setId(chId++);
System.out.println("CHID :: "+chId);
System.out.println("I :: "+i);
ch[i].setText(names[i]);
ll.addView(ch[i]);
}
for (int i = 0; i < names.length; i++) {
final int j = i;
ch[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView,
boolean isChecked) {
System.out.println("Checked ID :: " + ch[j].getId());
}
});
}
}
}
Views added dynamically do not have an ID until you specifically set them. So you need to call view.setId() on the view when you're adding to your layout, else you won't be able to reference it with view.getId().
I experienced a similar issue a while back when trying to dynamically create a RelativeLayout and positions the inner views relative to each other; they wouldn't align how they should have because the ID's didn't exist until I explicitly set one for them.
Also, why are you doing this:
ch.getId();
ch.setId(1);
That makes absolutely no sense. Take it out.
And also, you're going to need a reference linking the CheckBox to the View you want to delete. In this case, I would make a new ArrayList of Objects that have both a CheckBox and a View inside of it, IE.
public Class MyRow{
CheckBox c;
View v;
public MyRow() { }
}
Then when adding your views dynamically, add them to your MyRow or whatever class, then add that class to an ArrayList, and boom, you now have references between them and can remove the correct ones.