I am dynamically generating checkboxes in my program like so:
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
From what I've been able to test, this work fine for adding checkboxes to my table. The problem I'm encountering is that I want to be able to have something happen when a checkbox is checked, which I am unsure of how to do without knowning the id. Is there some way to get around this or get the id of the checkbox that has been checked when the onCheckBoxClick() method is called?
You don't need to know the ID because you already have the checkbox as on object.
Use this:
item1.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
if(item1.isChecked()){
System.out.println("Checked");
}else{
System.out.println("Un-Checked");
}
}
});
An other possibility:
item1.setOnCheckedChangeListener(new OnCheckedChangeListener()
{
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked)
{
if ( isChecked )
{
// perform logic
}
}
});
Assign id via code (programmatically)
1.Manually set ids using someView.setId(int);
2.The int must be positive, but is otherwise arbitrary.
Then you can access that id.
It think this would help you.
You have created TableRow and CheckBox you should set id pragmatically like this
public void addNewItem(String item, TableLayout tablel) {
TableRow row = new TableRow(this);
row.setId(i);//i is a positive int value
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
CheckBox item1 = new CheckBox(this);
row.setId(j);//j is a positive int value
item1.setText(item);
row.addView(item1);
tablel.addView(row, i);
i++;
You can check this SO question
int chkBoxId = 10;
int tableRowId = 100;
String texts[] = {"Text1", "Text2", "Text3", "Text4", "Text5"};
CheckBox[] chkBoxes;
private TableLayout tableLayout;
#Override
protected void onCreate(Bundle savedInstanceState) {
// TODO Auto-generated method stub
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_dynamic_chk_box);
tableLayout = (TableLayout) findViewById(R.id.tableLayout);
chkBoxes = new CheckBox[texts.length];
for(int i = 0; i < 5; i++) {
TableRow row = new TableRow(this);
TableRow.LayoutParams params = new TableRow.LayoutParams(TableRow.LayoutParams.WRAP_CONTENT);
row.setLayoutParams(params);
chkBoxes[i] = new CheckBox(this);
chkBoxes[i].setId(chkBoxId++);
row.setId(tableRowId);//tableRowId is a positive int value
chkBoxes[i].setText(texts[i]);
row.addView(chkBoxes[i]);
tableLayout.addView(row, i);
tableRowId++;
}
for (int i = 0; i < texts.length; i++) {
final int j = i;
chkBoxes[j].setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(isChecked) {
int checkedId = chkBoxes[j].getId();
Toast.makeText(DynamicCheckBoxActivity.this,
String.valueOf(checkedId),
Toast.LENGTH_SHORT).show();
} else {
int unCheckedId = chkBoxes[j].getId();
System.out.println("Uncheck ===> " + String.valueOf(unCheckedId));
}
}
});
}
}
Related
I have many similar cases, when I reach to the end and return back then my options of radiogroup and checkboxes adds one more instance of it.
eg;
radio button options before scrolling "
option1
option 2 " after scrolling I have "option1 option2 option1 option2 " and so on..
#Override
public void onBindViewHolder(final MyHolder holder, final int position) {
final MyData mData = dataList.get(position);
switch (holder.getItemViewType()) {
case 1:
holder.textView0.setText(mData.getText());
final int radioCount = mData.getTextFields().size();
for (int i = 0; i < radioCount; i++) {
RadioButton radio = new RadioButton(context);
radio.setId(View.generateViewId());
radio.setText(mData.getTextFields().get(i).getName());
holder.radioGroup.addView(radio);
radio.setOnClickListener(new View.OnClickListener() {
public void onClick(View view) {
//do something
}
});
}
break;
case 2: holder.textView1.setText(mData.getText());
List<Object> selectList1= new ArrayList<>() ;
int Option_Count = mData.getTextFields().size();
for (int i = 0; i < Option_Count; i++) {
final TableRow row = new TableRow(context);
row.setId(i);
row.setLayoutParams(new ViewGroup.LayoutParams(ViewGroup.LayoutParams.FILL_PARENT, ViewGroup.LayoutParams.WRAP_CONTENT));
CheckBox checkBox = new CheckBox(context);
checkBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
String joined="";
if (b) {
selectList1.add((String) compoundButton.getText());
joined = TextUtils.join(", ", selectList1);
} else {
selectList1.remove((String) compoundButton.getText());
joined = TextUtils.join(", ", selectList1);
}
if(b){
} }
});
checkBox.setId(i);
checkBox.setText(mData.getTextFields().get(i).getLabel());
row.addView(checkBox);
holder.linearLayout1.addView(row);
}
break;
}
}
This is a standard behaviour of the RecyclerView. Holders are reusable, when user scrolls, the onBindViewHolder() is called and radio buttons are added again.
The question is, how to make it right? You can initialize your views in onCreateViewHolder(). Is it possible for you? I don't know your data model. For example, you can add your radio buttons etc. in each constructor of your custom Viewholder class.
1.here all my code.
2.for create dynamic checkbox for check or uncheck all checkboxes
{ final String[][] itemContainer = new String[30][7];
TableLayout tblItemDetail;
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_item_code_release);
tblItemDetail = (TableLayout)findViewById(R.id.tblItemDetail);
try {
sqlItem = "";
sqlItem = "SELECT * from itm_mst";
rs = objDbConnect.getResultSet(sqlItem);
if (rs.next()) {
int i1 = 1;
do {
itemContainer[itemCount][0]=Integer.toString(i1++);
itemContainer[itemCount][6]="N"; //checkbox value
itemCount++;
} while (rs.next());
tblItemDetail.removeAllViews();
if (itemCount > 0) {
CheckBox tvchkall = new CheckBox(ItemCodeRelease.this); //header row checkbox for ckeck or uncheck all checkbox
tvchkall.setGravity(Gravity.CENTER);
tvchkall.setPadding(20, 0, 20, 0);
tvchkall.setText("Y");
headerRow1.addView(tvchkall);
tvchkall.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
if(buttonView.isChecked())
{
for(int a = 0 ; a < itemContainer.length ; a++)
{
for(int b = 0 ; b < itemContainer[a].length ; b++)
{
CheckBox chkb = (CheckBox)tblItemDetail.findViewById(a);
if ( chkb == null )
continue;
chkb.setChecked(true);
Log.i("Checkbox serrch","checked "+chkb.getText()+"ID +chkb.getId());
if(a == chkb.getId())
{
itemContainer[a][6] = "Y";
}
else
{
Log.i("Checkbox serrch","unchecked"+chkb.getText()+"ID "+chkb.getId());
itemContainer[a][6] = "N";
}}}}
});
tblItemDetail.addView(headerRow1);
int alternateRow1 = 0;
for (i = 0; i < itemCount; i++) {
TableRow bodyRow1 = new TableRow(ItemCodeRelease.this);
if (alternateRow1 % 2 == 0) {
bodyRow1.setBackgroundResource(R.color.statusalternateRow);
}
else {
bodyRow1.setBackgroundResource(R.color.statusRow);
}
final CheckBox cb1 = new CheckBox(ItemCodeRelease.this); //body row of checkbox
cb1.setId(i);
cb1.setGravity(Gravity.CENTER);
cb1.setPadding(20, 0, 20, 0);
bodyRow1.addView(cb1);
cb1.setOnCheckedChangeListener(new OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
// TODO Auto-generated method stub
for(int a = 0 ; a < itemContainer.length ; a++)
{
for(int b = 0 ; b < itemContainer[a].length ; b++)
{
if(buttonView.isChecked())
{
Log.i("Checkbox serrch","checked "+buttonView.getText()+"ID "+buttonView.getId());
if(a == buttonView.getId())
{
itemContainer[a][6] = "Y";
continue;
}}
else
{
itemContainer[a][6] = "N";
}}}}
});
bodyRow1.addView(tvBodySRNo1);
tblItemDetail.addView(bodyRow1);
alternateRow1++;
}}}
} catch (Exception e) { e.printStackTrace(); }}
Update [26-01-2016] : You can follow this to Check/UnCheck Dynamically created CheckBoxes.
Inside onCreate(Bundle bundle) { ... } add this :
Few Notes :
You need to give the Base Layout an ID if you use:
setContentView(R.layout.new_layout);
That is, when you set ContentView using layout xml.
You may need to create dummy ids in ids.xml in values folder for usability.
Please keep in mind that you can apply a similar logic for Layout created dynamically instead of using layout xml.
Please keep in mind that you can use similar logic for other Compound Buttons instead of CheckBox.
//Get Base Layout
LinearLayout linearLayout = (LinearLayout) findViewById(R.id.base_layout);
//Create new CheckBox
CheckBox mainCheckBox = new CheckBox(this);
//Create a new ids.xml in values folder and add dummy id there. Than use that dummy id for dynamically created views
mainCheckBox.setId(R.id.main_cb);
//Give a name to it
mainCheckBox.setText(R.string.mainCB);
//Add it to Base layout
linearLayout.addView(mainCheckBox, 0);
//Create other CheckBoxes...
CheckBox[] checkBoxes = new CheckBox[5];
for (int i = 0; i < 5; i++) {
checkBoxes[i] = new CheckBox(this);
checkBoxes[i].setText(String.format(Locale.getDefault(), "Child CheckBox %d", i + 1));
checkBoxes[i].setId(i+101);
linearLayout.addView(checkBoxes[i], i+1);
}
//Creating each checkbox individually:
CheckBox checkBox = new CheckBox(this);
checkBox.setText("Child CheckBox 6");
//Either add an integer value
checkBox.setId(106);
/*
* Or else use a dummy id
* checkBox.setId(R.id.child_cb);
*/
linearLayout.addView(checkBox, 6);
//Set listener to main CheckBox
mainCheckBox.setOnCheckedChangeListener(new CompoundButton.OnCheckedChangeListener() {
#Override
public void onCheckedChanged(CompoundButton buttonView, boolean isChecked) {
//Create an array of integer type to store all ids of child CBs
int[] ids = new int[] { 101, 102, 103, 104, 105, 106 };
/*
* You can also do
* int[] ids = new int[] { 101, 102, 103, 104, 105, R.id.child_cb };
*/
if(isChecked) {
Toast.makeText(getBaseContext(), "Checked", Toast.LENGTH_SHORT).show();
checkChildCBs(ids);
} else {
Toast.makeText(getBaseContext(), "Unchecked", Toast.LENGTH_SHORT).show();
unCheckChildCBs(ids);
}
}
});
Method to check all CheckBoxes
private void checkChildCBs(int[] ids) {
//Create CheckBox array of same size as that of ids
CheckBox[] checkBoxes = new CheckBox[ids.length];
//Run loop to check them
for (int i = 0; i < ids.length; i++) {
checkBoxes[i] = (CheckBox) findViewById(ids[i]);
checkBoxes[i].setChecked(true);
}
}
Method to unCheck all CheckBoxes
private void unCheckChildCBs(int[] ids) {
//Create CheckBox array of same size as that of ids
CheckBox[] checkBoxes = new CheckBox[ids.length];
//Run loop to unCheck them
for (int i = 0; i < ids.length; i++) {
checkBoxes[i] = (CheckBox) findViewById(ids[i]);
checkBoxes[i].setChecked(false);
}
}
/res/values/ids.xml :
<?xml version="1.0" encoding="utf-8"?>
<resources>
<item type="id" name="main_cb" />
<item type="id" name="child_cb" />
</resources>
Update : You can follow the below code to enable/disable Dynamically created CheckBoxPreferences.
Create a new file named preferences.xml in /res/xml/ directory :
<?xml version="1.0" encoding="utf-8"?>
<PreferenceScreen
xmlns:android="http://schemas.android.com/apk/res/android"
android:key="pref_screen">
</PreferenceScreen>
Than in your PreferenceActivity in onCreate() :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add preference xml file from /res/xml/
addPreferencesFromResource(R.xml.preferences);
}
Now we will create CheckBoxPreference dynamically :
// Get PreferenceScreen using the key as stated in preferences.xml
PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
// Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
// Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
for (int i = 0; i < cbPrefs.length; i++) {
cbPrefs[i] = new CheckBoxPreference(getActivity());
cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
}
/*
IF you want, you can also create new CheckBoxPreference individually like this :
cbPrefs[0] = new CheckBoxPreference(getActivity());
cbPrefs[0].setTitle("My Preference");
cbPrefs[0].setKey("my_pref_key");
prefScreen.addPreference(cbPrefs[0]);
cbPrefs[1] = new CheckBoxPreference(getActivity());
cbPrefs[1].setTitle("Some Name");
cbPrefs[1].setKey("some_pref_key");
prefScreen.addPreference(cbPrefs[1]);
and so on and so forth...
*/
// Now create and add a Preference to the PreferenceScreen
Preference preference = new Preference(getActivity());
preference.setTitle("Preference");
prefScreen.addPreference(preference);
// Now set onPreferenceClickListener to newly created preference.
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2",
"multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4",
"multiple_dynamic_pref_key_5"};
changePrefsState(prefKeys, cbPrefs);
return false;
}
});
Finally your onCreate() will look like this :
#Override
public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
// Add preference xml file from /res/xml/
addPreferencesFromResource(R.xml.preferences);
// Get PreferenceScreen using the key as stated in preferences.xml
PreferenceScreen prefScreen = (PreferenceScreen) findPreference("pref_screen");
// Now create a CheckBoxPreference array. The size of the array will be the number of required CheckBoxPreferences.
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[5]; // You can set any number you want. This will allow you to create 5 CheckBoxPreferences.
// Run loop to create CheckBoxPreferences and add them to the PreferenceScreen.
for (int i = 0; i < cbPrefs.length; i++) {
cbPrefs[i] = new CheckBoxPreference(getActivity());
cbPrefs[i].setTitle("Dynamically created multiple Pref " + (i+1));
cbPrefs[i].setKey("multiple_dynamic_pref_key_" + (i+1));
prefScreen.addPreference(cbPrefs[i]); // Adds the newly created CheckBoxPreference to the PreferenceScreen
}
// Now create and add a Preference to the PreferenceScreen
Preference preference = new Preference(getActivity());
preference.setTitle("Preference");
PreferenceScreen.addPreference(preference);
// Now set onPreferenceClickListener to newly created preference.
preference.setOnPreferenceClickListener(new Preference.OnPreferenceClickListener() {
#Override
public boolean onPreferenceClick(Preference preference) {
String[] prefKeys = new String[] {"multiple_dynamic_pref_key_1", "multiple_dynamic_pref_key_2",
"multiple_dynamic_pref_key_3", "multiple_dynamic_pref_key_4",
"multiple_dynamic_pref_key_5"};
changePrefsState(prefKeys, cbPrefs);
return false;
}
});
}
// This function is called when you click on preference to check/uncheck CheckBoxPrefs.
private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
try {
for (int i = 0; i < prefKeys.length; i++) {
checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
// Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
if (checkBoxPreferences[i].isChecked())
checkBoxPreferences[i].setChecked(false);
else
checkBoxPreferences[i].setChecked(true);
}
} catch(Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
Old :
private void someFunction() {
String[] prefKeys = new String[] {"pref_key_1", "pref_key_2", "pref_key_3", "pref_key_4", "pref_key_5"};
CheckBoxPreference[] cbPrefs = new CheckBoxPreference[prefKeys.length];
changePrefsState(prefKeys, cbPrefs);
}
private void changePrefsState(String[] prefKeys, CheckBoxPreference[] checkBoxPreferences) {
try {
for (int i = 0; i < prefKeys.length; i++) {
checkBoxPreferences[i] = (CheckBoxPreference) findPreference(prefKeys[i]);
// Check if CheckBozPreference is Checked. If yes than unCheck it else Check it
if (checkBoxPreferences[i].isChecked())
checkBoxPreferences[i].setChecked(false);
else
checkBoxPreferences[i].setChecked(true);
}
} catch(Exception e) {
Toast.makeText(getActivity().getBaseContext(), e.getMessage(), Toast.LENGTH_LONG).show();
}
}
The above example works for both Dynamically created preferences and XML defined preferences.
You just need to pass the keys and pref type.
You can make different changePrefsState(arg1, arg2) { ... } for different Preference types.
main checkbox for check all checkbox.
CheckBox tvchkall = new CheckBox(ItemCodeRelease.this);
tvchkall.setId(101);
tvchkall.setOnClickListener(getOnClickDoSomething(tvchkall));
listner that check all checkbox which is dynamicall creater.
View.OnClickListener getOnClickDoSomething(final CheckBox chk) {
return new View.OnClickListener() {
public void onClick(View v) {
if (chk.getId() == 101) {
if (chk.isChecked()) {
for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
itemContainer[a][6] = "Y";
CheckBox cb1 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
cb1.setChecked(true);
}
} else {
for (int a = 1; a < tblItemDetail.getChildCount(); a++) {
itemContainer[a][6] = "N";
CheckBox cb11 = (CheckBox) ((TableRow) tblItemDetail.getChildAt(a)).getChildAt(1);
}
}
} else {
if (chk.isChecked()) {
for (int a = 0; a < itemContainer.length; a++) {
for (int b = 0; b < itemContainer[a].length; b++) {
if (a == chk.getId()) {
itemContainer[a][6] = "Y";
}
}
}
} else {
for (int a = 0; a < itemContainer.length; a++) {
for (int b = 0; b < itemContainer[a].length; b++) {
if (a == chk.getId()) {
itemContainer[a][6] = "N";
}
}
}
}
}
}
};
}
Can Anybody help me? checkbox can't create dynamically . Just like sometimes I use the program create 6 checkboxes. Sometimes I create 8 checkboxes. I want to set each checkbox a event to catch the time when it's checked.In the following way, I get an error:Cannot refer to a non-final variable i inside an inner class defined in a different method.Change modifier of "i" to final.
The mCheckTime is a long array.
for(int i=0;i<optionsNum;i++){
mCheckBox[i]=new CheckBox(this);
mCheckBox[i].setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isCheck){
if (mCheckBox[i].isChecked()) {
mCheckTime[i] = System.currentTimeMillis();
}
}
};
if your content view is LinearLayout, try
final CheckBox mCheckBox = new CheckBox(this);
mCheckBox
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isCheck) {
if (mCheckBox.isChecked()) {
mCheckBox.setText(System.currentTimeMillis() + "");
}
}
});
LayoutParams params = new LinearLayout.LayoutParams(
LinearLayout.LayoutParams.WRAP_CONTENT,
LinearLayout.LayoutParams.WRAP_CONTENT);
addContentView(mCheckBox, params);
======EDIT======
or try this
LinearLayout layout = new LinearLayout(this);
layout.setOrientation(LinearLayout.VERTICAL);
setContentView(layout);
CheckBox[] mCheckBox = new CheckBox[6];
for (int i = 0; i < 6; i++) {
mCheckBox[i] = new CheckBox(this);
mCheckBox[i].setText(i + "");
mCheckBox[i]
.setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener() {
public void onCheckedChanged(CompoundButton buttonView,
boolean isCheck) {
if (isCheck) {
Toast.makeText(MainActivity.this,
System.currentTimeMillis() + "",
Toast.LENGTH_SHORT).show();
}
}
});
layout.addView(mCheckBox[i]);
}
Thank you very much. I use a final variable j to replace i inside the inner class.
for(int i=0;i<optionsNum;i++){
final int j = i;
mCheckBox[i]=new CheckBox(this);
mCheckBox[i].setOnCheckedChangeListener(new CheckBox.OnCheckedChangeListener(){
public void onCheckedChanged(CompoundButton buttonView, boolean isCheck){
if (mCheckBox[i].isChecked()) {
mCheckTime[i] = System.currentTimeMillis();
}
}
};
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.
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.