Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Creating buttons and separating there functionality android

Tags:

java

android

my app have action bar on top of windows. Where are some buttons. Buttons count and there functions is changing depending on activity user are.

I want to write a class with methods addFirstButton, removeFirstButton and so on. So i other classes i want to do this:

MyButtons myButtons = new MyButtons();    
myButtons.addFirstButton();

So there is everything alright, but how to create a listener button if i want to do this ?

Normally i would do this:

    Button backButton = (Button) customNav.findViewById(R.id.back);     
    backButton.setOnClickListener(new View.OnClickListener() {
            public void onClick(View v) {
                Toast.makeText(Action_Bar_TestingActivity.this, "BACK", Toast.LENGTH_SHORT).show();
            }
        });

But i want that this would be in MyButtons class and method somehow would return a listener to that action.

So any ideas if this possible ?

Thanks.

like image 780
Streetboy Avatar asked Nov 22 '25 12:11

Streetboy


1 Answers

If you're programming an Action Bar, then you can handle its "buttons" in onOptionsItemSelected(). For more information, see here: http://developer.android.com/guide/topics/ui/menus.html

If you are supporting Android 1.6-2.x, you can make a copy of the ActionBarCompat sample app. It will use some of the same XML flags as >=3.x ActionBar, but not all functionality is emulated. You may also consider using Action Bar Sherlock.

If you want to set and get your onClickListeners, you can. Nothing says you have to instantiate the click listener inside the button. But you'll have to do some bookkeeping. At the least, instantiate the listener outside your button array and pass it in.

Here's how I make a standalone click listener:

    Button.OnClickListener mTakePicOnClickListener = 
    new Button.OnClickListener() {
    public void onClick(View v) {
        dispatchTakePictureIntent(ACTION_TAKE_PHOTO_B);
    }
};

And here's where I attach it to a button (trivial example):

    private void setBtnListener( 
        Button btn, 
        Button.OnClickListener onClickListener ) {
        btn.setOnClickListener(onClickListener);            
}

(If you want to see what this function really looks like, it's part of the Capturing Photos sample app.)

But I think you can see how you could use this function internal to MyButtons.

like image 129
Sparky Avatar answered Nov 24 '25 02:11

Sparky



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!