Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Button array onclicklistener

I have set up 10 buttons in xml and added to main activity. I show only 2. All button just change a variable and button colors. Is there a method to group all the button to a single onclicklistener and use switch to check which button was pressed. using separate onclicklistener seems like allot of waisted space.

@Override
protected void onCreate(Bundle savedInstanceState) {
    super.onCreate(savedInstanceState);
    setContentView(R.layout.activity_main);

    f1 =(Button) findViewById(R.id.f1);
    f2 =(Button) findViewById(R.id.f2);

    f1.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clearbutton();
            f1.setBackgroundColor(Color.RED);
            intbtnSelect=0; 
        }
    });

    f2.setOnClickListener(new View.OnClickListener() {
        @Override
        public void onClick(View v) {
            clearbutton();
            f2.setBackgroundColor(Color.RED);
            intbtnSelect=1;
        }
    });
like image 397
Bobby Avatar asked Feb 15 '23 21:02

Bobby


1 Answers

You can implement OnClickListener into your Activity. For instance

public class MyActivity extends Activity implements View.OnClickListener {       
     @Override
     protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_main);

        f1 =(Button) findViewById(R.id.f1);
        f1.setOnClickListener(this);

        f2 =(Button) findViewById(R.id.f2);
        f2.setOnClickListener(this);
     }
}

Them you have to implement the onClick method and switch upon view.getId():

@Override
public void onClick(View v) {
    switch (v.getId()) {
    case R.id.f1:
        // your code here
        break;
    case R.id.f2:
        // your code here 
        break;
    }
}
like image 64
Blackbelt Avatar answered Feb 23 '23 03:02

Blackbelt