johnson johnson - 4 months ago 14
Android Question

how to create button dynamically and add click event to button in android

I need to add a button to the activity in android.

And when I click this button I need to get which checkbox is checked and unchecked.My code is

package com.example.a;
import android.os.Bundle;
import android.app.Activity;
import android.view.Menu;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.LinearLayout;
import android.widget.ScrollView;
import android.view.View.OnClickListener;
public class MainActivity extends Activity {

@Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
ScrollView sv = new ScrollView(this);
LinearLayout ll = new LinearLayout(this);
ll.setOrientation(LinearLayout.VERTICAL);
sv.addView(ll);
for(int i = 0; i < 20; i++) {
CheckBox cb = new CheckBox(this);
cb.setText("I'm dynamic!");
ll.addView(cb);
}
this.setContentView(sv);


}


@Override
public boolean onCreateOptionsMenu(Menu menu) {
// Inflate the menu; this adds items to the action bar if it is present.
getMenuInflater().inflate(R.menu.main, menu);
return true;
}

}

Answer

Make your for loop as :

for (int i = 0; i < 20; i++) {
        CheckBox cb = new CheckBox(this);
        cb.setId(i);
        cb.setText("I'm dynamic!");
        ll.addView(cb);
    }

Then add this code :

 Button bt = new Button(this);
 sv.addView(bt);
    bt.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View view) {
            for (int i = 0; i < 20; i++) {
                CheckBox cb = (CheckBox) ll.getChildAt(i);
                cb.isChecked();
            }
        }
    });