Reputation: 4164
Just wondering if any of you guys could help me to access an element from an 'include' layout file which is inside not an activity but a fragment?
Most posts tell me to do something like that: How to access Button inside "include" layout but as I am not on an activity the listener for the image won't work.
Ps: The listener works (opens the nav drawer) when I call an element which is not in the include file but on the fragment layout.
That's what I have inside the onCreateView method for my fragment:
View myLayout = view.findViewById(R.id.layout_top_bar);
image = (ImageView) myLayout.findViewById(R.id.image_left_top_bar);
image.setOnClickListener(new View.OnClickListener() {
@Override
public void onClick(View v) {
MainActivity mainActivity = (MainActivity)getActivity();
mainActivity.openMenuDrawer();
}
});
That's my include layout file:
<RelativeLayout
xmlns:android="http://schemas.android.com/apk/res/android"
android:id="@+id/layout_top_bar"
android:layout_width="match_parent"
android:layout_height="match_parent"
android:padding="8dp">
<ImageView
android:id="@+id/image_left_top_bar"
android:layout_width="wrap_content"
android:layout_height="wrap_content"
android:src="@drawable/hamburger_icon" />
And that's how I'm including it within the fragment layout file:
<include layout="@layout/top_bar" />
Thanks very much for any help on that! :)
Upvotes: 1
Views: 3991
Reputation: 2636
You can access it directly with the root layout of your fragment like this.
image = view.findViewById(R.id.image_left_top_bar);
In case we are adding the layout dynamically by inflating it, we use the approach you mentioned above but that's not needed here.
Upvotes: 2
Reputation: 5600
Put a id to the Layout and later access to the elemento.
View myLayout = findViewById( R.id.layout );
View myView = myLayout.findViewById( R.id.item );
Upvotes: 0