简体   繁体   中英

Android Data Binding SetSupportActionBar

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

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/>

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);
<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>

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);

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM