Android Data Binding SetSupportActionBar
Asked Answered
C

4

16

Hi I wonder if there is an xml tag for this function using Android Data Binding Library or how to achieve this without findViewById() method

Thank You

Cambist answered 6/1, 2016 at 15:36 Comment(1)
developer.android.com/reference/android/view/View.html there are other methods in link belowBensky
G
19

You can access the instance of the toolbar using views by id function

<android.support.v7.widget.Toolbar
            android:id="@+id/toolbar"
            android:layout_width="match_parent"
            android:layout_height="?attr/actionBarSize"
            android:background="?attr/colorPrimary"
            app:layout_scrollFlags="scroll|enterAlways"
            app:popupTheme="@style/AppTheme.PopupOverlay" />

then on your onCreate() method do the following

ActivityGalleryBinding binding = DataBindingUtil
    .setContentView(this, R.layout.activity_gallery);
binding.setViewModel(new GalleryModel(this));
//set it like this
setSupportActionBar(binding.<location>.<of>.<your>.toolbar);

if your toolbar is inside other xml component (referenced with <include/>) you still can access it as long as you provide and @id to the <include/>

Groomsman answered 7/4, 2016 at 2:32 Comment(3)
what if toolbar is included in the include layout? Or if there is multiple view in included layout?Dewitt
i have used DataBinding in custom toolbar and using <include> , the toolbar is used in activity_main.xml, but i have not used DataBinding in activity_main.xml, then how to get toolbarBinding(custom toolbar) in mainActivity.Topology
How about binding.root.toolbar if it is inside <include> ?Staton
K
1

Make project in Android Studio then you can use below code for accessing toolbar:

ActivityMainBinding binding = DataBindingUtil.setContentView(this, R.layout.activity_main);
setSupportActionBar(binding.toolbar);
Kerbela answered 14/9, 2016 at 8:25 Comment(0)
L
0
<layout xmlns:android="http://schemas.android.com/apk/res/android"
    xmlns:app="http://schemas.android.com/apk/res-auto" 
    >
  <data>
    <variable
        type="com.example.viewModel"
        name="viewModel"
        />
  </data>
  <android.support.v7.widget.Toolbar
      android:layout_width="match_parent"
      android:layout_height="?actionBarSize"
      app:title="@{viewModel.title}"/>
</layout>
Lacee answered 16/6, 2018 at 9:7 Comment(1)
can you share viewmodel code where you change the title?Troublesome
C
0

You can use it this way. This Answered for me After many searches.

  1. use id for your include, example my toolbar id is tb and include id is mtoolbar

  2. now use setSupportActionBar(mainBinding.mtoolbar.tb);

Caithness answered 17/12, 2021 at 8:26 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.