setOnClick for 100 buttons - android

I have 100 buttons (from button000 to button 999). Is there any way to setOnClick for all of them? Because all button have the same function.
Thanks in advance.

If your buttons are inside a layout then do like this.
int childcount = ll.getChildCount();
for (int i=0; i < childcount; i++){
View v = ll.getChildAt(i);
v.setOnCLickListener(this);
}

Buddy try this way
import android.view.View.OnClickListener;
public class MyActivity extends Activity implements OnClickListener {
#Override public void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.main);
Button buttonA = (Button) findViewById(R.id.buttonA);
buttonA.setOnClickListener(this);
Button buttonB = (Button) findViewById(R.id.buttonB);
buttonB.setOnClickListener(this);
}
//etc... etc...
public void onClick(View v) {
switch (v.getId()) {
case R.id.buttonA:
// do something
break;
case R.id.buttonB:
// do something else
break;
}
}

At right now I can say easiest way in
use button000.setOnclicklistener(this);
:
:
button999.setOnclicklistener(this);
and implement Onclicklistener in this current class....

if you are sure that it's the best way for your app to create 1000 buttons, then it will be something like this:
Button [] my_button=new Button[1000];
LinearLayout ll=(LinearLayout)findViewById(R.id.mylayout);
for (int i=0;i<1000;i++){
my_button[i]=new Button(this);
my_button[i].setLayoutParams(new LayoutParams(LayoutParams.FILL_PARENT,
LayoutParams.WRAP_CONTENT));
my_button[i].setText("button "+i);
ll.addView(my_button[i]);
my_button[i].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
////click event
}
});
}

Just add your buttons in an array and
Just loop the buttons and on a listener you can call the following block of code:
for (int i=0; i < buttonArray.length; ++i){
buttonArray[i].onClick(this);
}

there are two methods one is you can set onClick in xml layout file by onClick method you can define the method, that should be invoked when button is clicked. This method is appropriate when you define buttons in xml.
If you are adding buttons in Activity, and if you are adding in a loop then you can do as
for(int i=0; i<100; i++)
{
//Create and Add button
btn.setOnClickListener(new OnClickListener()
{
public void onClick(View view)
{
//Operations
}
});
}

Best way to make Button Dynamically like
Integer[] button_Ids = {R.id.btn000,R.id.btn001...............,R.id.btn999};
for(int i=0;i<100;i++)
{
Button btn = (Button)findViewById(button_ids[i]);
btn.setOnClickListner(this);
}
#Override
public void onClick(View v)
{
Toast.make(getApplicationContext,"Hello",1000).show();
}

If all buttons have exactly same functionality then you can simple use
private OnClickListener mListenr=new OnClickListener(
#Override
public void onClick(View v) {
//Whatever you want
}
for(int i=0; i<100; i++)
{
mButton[i].setOnClickListener(mListenr);
}
you can refer this to see ways to implement listener.

Related

Use a button to add other buttons, editText etc.

I need to be able to add buttons to a layout using an "add" button. The problem is that I need each button to have an OnClickListener()/onClick method. I was thinking every time the "add" button is pressed then i would add a new button to an array but im not sure add the listener and implement an onClick method for each button I create.
public class MainActivity extends ActionBarActivity {
#Override
protected void onCreate(Bundle savedInstanceState) {
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
final SmartChronometer chrono = (SmartChronometer) findViewById(R.id.chrono);
final Button start = (Button) findViewById(R.id.button2);
start.setOnClickListener(new View.OnClickListener() {
public void onClick(View v) {
if (chrono.isRunning())
chrono.pause();
else {
chrono.chronoStart();
}
}
});
}
I need to add chronomoter,button and listeners every time I click an "Add" button.
set all the clicklisteners as you wich!
call findViewById(R.id.btnSecond).setVisibility(View.GONE); on creat, then when clickin the first button
Button btnSecond;
...
public void onClick(View v) {
findViewById(R.id.btnSecond).setVisibility(View.VISIBLE);
if (btnSecond.getVisibility() == View.VISIBLE); {
findViewById(R.id.btnThird).setVisibility(View.VISIBLE);}
}
this way you can put all your information in the java file and all buttons in xml, but they will be hidden until click.
This is one way, other answer my come. Good Luck :)
implements OnClickListener
Button add = (Button) findViewById (R.id.addButton);
add.setOnClickListener (this);
List<Button> buttons = new ArrayList <Button>();
for (int i = 0; i < buttons.size (); i++){
buttons.get (i).setOnClickListener (this);
}
#Override
public void onClick (View v){
for (int i = 0; i < buttons.size (); i++){
if (v.getId () == buttons.get (i).getId ()){
// do stuff you want
}else if (v.getId() == R.id.addButton){
//add button
}
}
}
Hope this will work, didnt test it.

get OnClick() from programmatically added buttons?

i have added some button in a layout:
LinearLayout row = (LinearLayout)findViewById(R.id.KeysList);
keys=db.getKeys(console);
my_button=new Button[keys.size()];
for (bt=0;bt<keys.size();bt++){
my_button[bt]=new Button(this);
my_button[bt].setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT,LayoutParams.FILL_PARENT));
my_button[bt].setText(keys.get(bt));
my_button[bt].setId(bt);
row.addView(my_button[bt]);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[bt].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), keys.get(bt), 0).show();
}
}
});
}
I want to know which button is clicked and how to get text of the clicked button?And I think using bt here dose not seem to work!
This code is running. I hope it help you :)
final ArrayList<String> Keys = new ArrayList<String>();
for(int i = 0; i < 10; i ++){
Keys.add("Keys is : " + String.valueOf(i));
}
LinearLayout Row = (LinearLayout)findViewById(R.id.KeysList);
final Button[] my_button = new Button[Keys.size()];
for (int bt = 0; bt < Keys.size(); bt ++){
final int Index = bt;
my_button[Index] = new Button(this);
my_button[Index].setLayoutParams(new LayoutParams(LayoutParams.MATCH_PARENT,LayoutParams.WRAP_CONTENT));
my_button[Index].setText(Keys.get(Index));
my_button[Index].setId(Index);
my_button[bt].setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
if (my_button[Index].getId() == ((Button) v).getId()){
Toast.makeText(getBaseContext(), Keys.get(Index), 0).show();
}
}
});
Row.addView(my_button[Index]);
}
ExampleProject id : Your project
You should probably use View#setTag to set some arbitrary data you'd like associate with the Button. Then you can just instantiate only one OnClickListener that then uses getTag and acts on that data in whatever way you need.
Another way is to have your Activity listen to all button clicks and then you just filter respective to the ID. You should not get the text of the button and use that at all. You should use your own type of identifier, ideally the idea should be enough. Or perhaps you use setTag as #qberticus described.
Consider This example :
public class MainActivity extends Activity implements View.OnClickListener
{
LinearLayout linearLayout;
Button [] button;
View.OnClickListener listener;
#Override
public void onCreate(Bundle savedInstanceState)
{
super.onCreate(savedInstanceState);
setContentView(R.layout.activity_main);
linearLayout=(LinearLayout)findViewById(R.id.parent_lay);
String[] array={"U123","U124","U125"};
int length=array.length;
System.out.println("11111111111111111111111111");
button=new Button[length];
for(int i=0;i<length;i++)
{
button[i]=new Button(getApplicationContext());
button[i].setId(i);
button[i].setText("User" + i);
button[i].setOnClickListener(this);
linearLayout.addView(button[i]);
}
}
#Override
public void onClick(View view)
{
view.getId();
Button button=(Button)findViewById(view.getId());
button.setText("Changed");
}
}
This works fine :)

Dynamic Buttons and OnClickListener

Say I have buttons that are created dynamically:
for(int j = 0; j < spirits.length;
j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new SpiritsClickListener());
cabinet_layout.addView(imgBtn);
}
I want to change the text of the button every time it's pressed (On - Off)
How can I reference the buttons within the OnClickListener class?
in your onClickListener, you have a function called onClick(View v){} where v is the View that was clicked. You may use v to get details about the button, including its ID. You can also take this view, and if you know it is a button, cast it to a button.
Button clicked = (Button)v;
You can then use it in your javacode just as you would normally use a button.
Why don't you just call new OnClickListener() inside that loop like this
for(int j = 0; j < spirits.length;j++){
Button imgBtn = new Button(v.getContext());
imgBtn.setLayoutParams(new LayoutParams(LayoutParams.WRAP_CONTENT, LayoutParams.WRAP_CONTENT));
imgBtn.setMinimumWidth(100);
imgBtn.setMinimumHeight(100);
imgBtn.setId(j+1);
imgBtn.setTag(spirits[j]);
imgBtn.setText(spirits[j]);
imgBtn.setOnClickListener(new OnClickListener() {
#Override
public void onClick(View v) {
//do what you need to do here
}
});
cabinet_layout.addView(imgBtn);
}
Create an OnClickListener for dynamically created buttons as:
// Create Listener for Button
private OnClickListener SpiritsClickListener = new OnClickListener()
{
#Override
public void onClick(View view) {
// TODO Auto-generated method stub
Button btn = (Button) view;
String btnText = btn.getText();
if(btnText.equalsIgnoreCase("On")){
btn.setText("Off");
}else{
btn.setText("On");
}
}
};
add this Listener to dynamically created buttons as:
imgBtn.setOnClickListener(SpiritsClickListener);

How to check which ImageButton was prssed?

I have lots of image buttons. User can press any of those button and i need to know which button is pressed. These buttons appears dynamically so i don't know how much of them will be.
For one image button i would write this listener:
ImageButton ib = new ImageButton(this);
ib.setOnClickListener(new View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TravelBite.this, "test", Toast.LENGTH_SHORT).show();
}
});
But how to do one listener for all my Images Buttons? Can i recognize which button was pressed by it's tag ? Like tag would be ID from sqlite.
Also i put image to button with this code:
button.setImageDrawable( testPic );
button is ImageButton and testPict is drawable (image)
But when i press this button it don't show that it is pressed if i do this:
button.setBackgroundColor(R.color.transparent_background);
I had to do this because i just want to see Buuton image which i could press and recognize what i pressed.
Thanks.
ok what you can do is that you can write a single callback function and then set it to each and every button it will allow you to handle each button with a sing function like :
View.OnClickListener btn_listener = View.OnClickListener() {
#Override
public void onClick(View v) {
// Do whatever work you want.
int id = v.getid();
// check for id and do you task.
}
Arraylist<Button> btn_group = new Arraylist<Button>;
or
Arraylist<int> btn_id_group = new ArrayList<int>;
for (int i =0; i < 10; i++) {
Button btn = new Button(getApplicationContext());
btn.setId(i);
btn_id_group.add(i) or btn_group.add(btn);
btn.SetOnClickListener(btn_listener);
}
I think it will work for you.
You can use View.setTag(object) and View.getTag() and store in it sqlite id. Something like this:
View.OnClickListener listener = View.OnClickListener() {
#Override
public void onClick(View v) {
Toast.makeText(TravelBite.this, (String)v.getTag(), Toast.LENGTH_SHORT).show();
//or some function that do somthing useful
//if( ((String)v.getTag).equals("image1") ){} or anything else
}
And in for loop:
String tagFromSqlite = "image1";
ImageButton ib = new ImageButton(this);
ImageButton.setTag(tagFromSqlite);
ib.setOnClickListener(listener);
final OnClickLisener listener = new OnClickListener() {
public void onClick(View v){
switch((Integer)v.getTag()){
case R.id.zero:
break;
case R.id.one:
break;
case R.id.two:
break;
}
}
}
//when init the Buttom
ImageButton btn = new ImageButton(Context);
btn.setTag(NUMBER);
you'll have to manually assign ID's to keep them separated - I had to do something similar (1000 was the base ID I chose to add upon as well)
Although View v in the listener refers to the button pressed, when you programmatically create buttons the id's are not unique and caused me issues, so that's why I set them specifically
View.OnClickListener btn_listener = View.OnClickListener()
{
#Override
public void onClick(View v)
{
//you can use v.getID() here
}
}
for (int i =0; i < 10; i++)
{
Button btn = new Button(getApplicationContext());
btn.setID( 1000 + i );
btn.SetOnClickListener(btn_listener);
}

Is it possible to write a for loop to assign listeners to many button with the same function where final ints are used?

I am writing an android application and I have 8 buttons on one view that all have the same function, so I wanted to assign the same functionality to each button using a for loop rather than writing out 8 pieces of separate code. However, an issue arises when I want to use the the counter from the for loop within the onClick function to help fire an intent, here's the code:
//array of button ids
public int [] pickPlayers = { R.id.pick_player_1a, R.id.pick_player_2a, R.id.pick_player_3a, R.id.pick_player_4a, R.id.pick_player_1b, R.id.pick_player_2b, R.id.pick_player_3b, R.id.pick_player_4b};
//button to be used in for loop
public Button b;
//for loop to assign same functionality to buttons in pickPlayers array
for(int i = 0; i<pickPlayers.length; i++){
b = (Button) findViewById(pickPlayers[i]);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent getContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(getContactIntent, i);
}
});
};
Hope that all makes sense, thanks to anyone who can help. :)
EDIT: This is the error I get: Cannot refer to a non-final variable i inside an inner class defined in a different method
The for loop is in my oncreate method the variables and buttons are outside
Yes you can't access variable in your inner classes if it's not declared as final. Simple workaround will be to create OnClickListener wrapper class.
private class MyListener implements Button.OnClickListener {
int pos;
public MyListener (int position) {
pos = position;
}
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent getContactIntent = new Intent(Intent.ACTION_PICK,ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(getContactIntent, pos);
}
}
and then use it in you code like this
//for loop to assign same functionality to buttons in pickPlayers array
for(int i = 0; i<pickPlayers.length; i++){
b = (Button) findViewById(pickPlayers[i]);
b.setOnClickListener(new MyListener(i));
}
Also if your buttons are in some ViewGroup you can use getChildAt and getChildCount to iterate them
ViewGroup parent;
// initialize the parent
int l = parent.getChildCount();
for (int i = 0 ; i < l ; i++) {
Button button = parent.getChildAt(i);
}
Just change your code like that:
//for loop to assign same functionality to buttons in pickPlayers array
for(int i = 0; i<pickPlayers.length; i++){
final int index = i;
b = (Button) findViewById(pickPlayers[i]);
b.setOnClickListener(new Button.OnClickListener() {
#Override
public void onClick(View v) {
// TODO Auto-generated method stub
Intent getContactIntent = new Intent(Intent.ACTION_PICK, ContactsContract.Contacts.CONTENT_URI);
startActivityForResult(getContactIntent, index);
}
});
};
This should do the job. Good luck!
If those buttons are decalred in XMl maybe you should set android:onClick listener to them through XML?
You have to define one method in your activity:
public void myHandler(View v) {
// Your stuff...
}
And add
android:onClick="myHandler"
to all of them?
Thanks.

Categories

Resources