BlackVegetable
BlackVegetable

Reputation: 13074

Android: Listener Pattern within onCreate()

So, I am again, asking a very basic question. I apologize for my ineptness but I guess I read the given tutorials on these topics poorly. My question is as follows:

I would like to use a "listener" pattern to handle button presses on my GUI. I believe an onClickListener is what I need to use to handle these button presses. However, I'm not sure if I should be creating and handling events that occur after the GUI is created within an onCreate method. The following code is within my onCreate method for one of my Activities:

View.OnClickListener upDownListener = new View.OnClickListener() 
    {       
        @Override
        public void onClick(View v) 
        {


            if(v == (upOneButton))
            {
                Log.d("OptionSelect", "Up One Button Pressed.");
                ops.getOptionList().get(0).incrementProbability(4);
            } . . .

This method being called updates some GUI text with a different number. It is being called, but the GUI isn't responding. I imagine this has to do with my attempt to use it within the onCreate method.

In short, what is a good and simple way to deal with user events within a GUI and where should this occur?

Thank you so much.

EDIT: Log.d() does in fact get called. Also, ops is an object of type OptionSelect which happens to be the type of the class in which the onCreate() call is made. Will that become an issue? Also, here is the method for incrementProbability():

public void incrementProbability(int numberOfOptions)
    {
        probability += (numberOfOptions - 1);
        if(probability > 100)
        {
            Log.i("OptionSelect", "Exceeded Maximum by " + (probability - 100));
            probability = 100;
        }
    }

Also, here is relevant code I should've included that is updating my GUI at the end of the onClick() method:

    private void refreshDisplay(TextView a, TextView b, TextView c, TextView d)
{
    a.setText(getOptionList().get(0).getProbability() + "");
    b.setText(getOptionList().get(1).getProbability() + "");
    c.setText(getOptionList().get(2).getProbability() + "");
    d.setText(getOptionList().get(3).getProbability() + "");

    a.invalidate();
    b.invalidate();
    c.invalidate();
    d.invalidate();
}

Thanks for the help so far!

Upvotes: 0

Views: 894

Answers (1)

Squonk
Squonk

Reputation: 48871

I personally prefer to have my Activities implement listener interfaces and add an onClick method to the Activity itself such as...

public class MyActivity extends Activity
    implements View.OnClickListener {

    ...

    @Override
    public void onClick(View v) {

        ...

    }
}

I then just use...

myGuiObject.setOnClickListener(this);

...whenever I want to set that method as the listener for any GUI object.

Upvotes: 4

Related Questions