53

Refer to the doc: http://android-developers.blogspot.com/2009/02/android-layout-tricks-2-reusing-layouts.html

I have a button inside the included layout, how can I access the button? I don't know the id! How can I define the OnClickListener...?

Please help...

joe
  • 51
  • 6
chow
  • 769
  • 2
  • 8
  • 10
  • This solution worked for me and it's pretty easy. https://stackoverflow.com/a/69703403/10116694 – Shibl Oct 25 '21 at 05:58

6 Answers6

90

The id you have with the include tag is assigned to the root View of the included layout. First get a reference to that View using findViewByid. Then you can call findViewById on that specific View to get a reference to a View inside the layout. So:

View myLayout = findViewById( R.id.cell1 ); // root View id from that link
View myView = myLayout.findViewById( R.id.someinnerview ); // id of a view contained in the included file
Jems
  • 11,560
  • 1
  • 29
  • 35
23

All you need is the id of the parent view:

enter image description here

In this example, the LinearLayout is the parent of the TextView I want from the included View.

I can now do this:

    View view = findViewById(R.id.include_title_layout);
    TextView titleTV = (TextView) view.findViewById(R.id.newsTitleTextView);
    titleTV.setText("Whatever");
Ojonugwa Jude Ochalifu
  • 26,627
  • 26
  • 120
  • 132
3

Actually include tags include all the elements in your root layout. So you can always access them using findViewById on your Activity.

Suppose you have a alayout.xml in which there is a include layout. Now in one of your activity A,inside onCreate you declared setContentView(R.layout.alayout) Now inside your include layout you might have a button with id myBtn. You can access that inside onCreate in the same way you could access it if it were in main layout: findViewById(R.id.myBtn)

Munim
  • 2,626
  • 1
  • 19
  • 28
3

You do know the id of the include. You can get that complete element, and then get one of its children starting from there.

Jeff Axelrod
  • 27,676
  • 31
  • 147
  • 246
Nanne
  • 64,065
  • 16
  • 119
  • 163
1

i think your mean is NavigationView. you can access to inner layout by this way:

NavigationView ngv= (NavigationView) findViewById(R.id.navigation_id);
View innerview =  ngv.getHeaderView(0);
TextView user_view= (TextView)innerview.findViewById(R.id.nav_name); //any you need
user_view.setText(user);
Abolfazl Miadian
  • 3,099
  • 2
  • 19
  • 15
0

works for me in java

        <include
            android:id="@+id/layout_infoProfile"
            layout="@layout/user_info_doctor_profile_layout"
            />



  preferences = mContext.getSharedPreferences(MyConstant.MY_SHARED_PREF,Context.MODE_PRIVATE);
     View view = mView.findViewById(R.id.layout_infoProfile);  
((TextView)view.findViewById(R.id.tv_name)).setText(preferences.getString(MyConstant.ROLE,MyConstant.NO_VALUE));
harry
  • 171
  • 1
  • 4