Question

We can use <include /> to include a layout into another.

I'm including activity_main.xml into activity_second.xml using <include />.

activity_main.xml has a <TextView /> and a <Button />. And the <Button /> has a handler doThis(View v){..} in MainActivity.java

How do I reuse the Button Handler in the SecondActivity.java

Was it helpful?

Solution

You can use Fragments for that

OTHER TIPS

There's no button handler thing. It is OnClickListener. And to reuse it either copy that source to second activity class or create MyActivity class which your MainActivity and SecondAcivity would extend and put common code there.

I did something similair to your question. Don't think it's better than using Fragments but in a nutshell.

You have your layout_main.xml. You can import other XML (menu.xml) into that like this:

<include
    android:id="@+id/layoutMenu"
    layout="@layout/menu" />

Create a Menu.java Class like this (I copied this from my own class so it is not complete but for the idea of it):

 public class Menu {

ImageView buttonNieuws;

public void set(Activity activity, String currentPage) {

    // Button NIEUWS
    buttonNieuws = (ImageView) activity.findViewById(R.id.button_nieuws);

    if (!currentPage.equals("nieuws")) {

        buttonNieuws.setOnClickListener(new OnClickListener() {
            @Override
            public void onClick(View view) {
                Intent intent = new Intent(view.getContext(),
                        Nieuws.class);
                view.getContext().startActivity(intent);
            }
        });

    } else {

        buttonNieuws.setImageDrawable(activity.getResources().getDrawable(
                R.drawable.button_nieuws_on));
    } ...

And then in your main Activity Class you can use code like this to link it all together:

 Menu menu = new Menu();
 menu.set(this, currentPage);

Huge drawback is that unlimited Activities get stacked on top of each other. This is my temporary solution because i didn't get into Fragments yet.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top