I have an application with a common Header in all layouts. I want that whenever the user clicks at the the ImageView with id btn_home, the app will go back to a specific activity, my “Main” for instance.
What is the best way to do that?
I know that I can define the onClick(View v) for every activity, but maybe there is a better way to do that. Even making every activity be some (via heritage) other that has the onClick(View v) defined sounds bad.
header.xml
<RelativeLayout ...>
<RelativeLayout android:id="@+id/relativeLayout1" ...>
<ImageView android:id="@+id/logo_cats"></ImageView>
<ImageView android:id="@+id/btn_home" ...></ImageView>
</RelativeLayout>
</RelativeLayout>
every layout
...
<include layout="@layout/header" android:id="@+id/header"
android:layout_height="wrap_content" android:layout_width="fill_parent" />
...
You can make a custom component out of your header and define ‘onClick()’ in it. For example, make a new class
Headerthat would extend a RelativeLayout and inflate your header.xml there. Then, instead of<include>tag you would use<com.example.app.Header android:id="@+id/header" .... No code duplication and the header becomes totally reusable.UPD: Here’s some code examples
header.xml:
activity_with_header.xml:
Header.java:
ActivityWithHeader.java:
In this example, Header.initHeader() can be moved inside Header’s constructor, but generally this method provides a nice way to pass on some useful listeners. Hope this will help.