Reputation:
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
Upvotes: 1
Views: 1019
Reputation: 290
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.
Upvotes: 1
Reputation: 75629
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.
Upvotes: 2