0

My Activity has multiple lists so I have defined MyClickListener as below:

My question is how I should instantiate this class:

 MyClickListener mMyClickListener = new MyClickListener();

Or maybe it is better to instantiate inside the onCreate(Bundle) and just define above. Whats considered the better way? I don't want too much in onCreate() its already full of stuff. Any thoughts on the declaration and instatiation? Whats the best way?

private class MyClickListener implements OnClickListener
{

    @Override
    public void onClick(View view) {

    }

}
4

2 回答 2

1

I use same kind of class mechanism as you mentioned in the question.

this is the way i use,

public class myActivity extends Activity
{
    private MyListener listener = null;

    private Button cmdButton = null;

    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.main);

                cmdButton = (Button) findViewById(R.id.cmdButton);
                cmdButton.setOnClickListener(getListener());

    }


    // method to fetch the listener object
    private MyListener getListener() 
    {
        if (listener == null) 
        {
            listener = new MyListener();
        }
        return listener;
    }

       private class MyListener implements Button.OnClickListener 
       {
             public void onClick(View v) 
             {
             }
       }
}
于 2012-09-22T02:05:46.890 回答
1

你为什么要首先实例化一个这样的监听器?当您将它分配给您的 listView 时,只需创建一个新的。

listView.setOnClickListener( new MyListener());
于 2012-09-22T03:34:54.997 回答