简体   繁体   中英

Android - what should I do to set the button listeners for the header in a single place?

I am trying to create button listeners for the header navigation so that the listeners can be in some single place.

I am hoping to make a method like this:

public void set_nav_listeners ( )
{
    Button planBusiness = (Button)findViewById(R.id.home_header);
    Button questions_header = (Button)findViewById(R.id.questions_header);

    learn_header.setOnClickListener(new Button.OnClickListener() 
{  
    public void onClick(View v) 
    {                   
      Intent myIntent = new Intent(ProblemioActivity.this, LearnActivity.class);
      ProblemioActivity.this.startActivity(myIntent);
    }
});

questions_header.setOnClickListener(new Button.OnClickListener() 
{  
    public void onClick(View v) 
    {                   
      Intent myIntent = new Intent(ProblemioActivity.this, QuestionsActivity.class);
      ProblemioActivity.this.startActivity(myIntent);
    }
}); 
}

and pass parameters in there that would make it work for every Activity. So something like this call would work:

public class RandomActivity extends Activity
{
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate(savedInstanceState);

        // For checking if the person is logged in.
        set_nav_listeners ( ---> What parameters can I pass so it would work? <---- );
        ...

Is that possible? How do I pull this off?

Thanks!

its better to create one Class and extend it.

public class RandomActivity extends BaseActivity

public class BaseActivity extends Activity {

    @Override
    public void setContentView(int layoutResID) {
        super.setContentView(layoutResID);



        findViewById(R.id.home_header).setOnClickListener(new OnClickListener() {

            @Override
            public void onClick(View v) {
                Toast.makeText(BaseActivity.this, "HITESTING!!!",
                        Toast.LENGTH_LONG).show();

            }
        });

    }

}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM