2
votes

I want to set a custom title bar for an activity, the title bar has a button bound to a command in the activity view model.

Somehow I wasn't surprised it didn't work.

Is it possible to do make it work?

The code:

MainView.cs:

[Activity]
public class MainView : MvxActivity
{
    protected override void OnCreate (Bundle savedInstanceState)
    {
       this.RequestWindowFeature(WindowFeatures.CustomTitle);
       base.OnCreate (savedInstanceState);
       this.Window.SetFeatureInt(WindowFeatures.CustomTitle, Resource.Layout.MainWindowTitle);
       SetContentView(Resource.Layout.MainView);
    }
}

The MainWindowTitle.axml:

<?xml version="1.0" encoding="utf-8"?>
<LinearLayout xmlns:android="http://schemas.android.com/apk/res/android"
     xmlns:local="http://schemas.android.com/apk/res-auto"
    android:orientation="vertical"
    android:layout_width="fill_parent"
    android:layout_height="fill_parent">
        <ImageButton
        android:id="@+id/search"
        android:src="@drawable/magnify"
        local:MvxBind="Click SearchCommand" />
    </LinearLayout>

MainViewModel.cs

 public class MainViewModel : MvxViewModel
    {
          public IMvxCommand SearchCommand { get; private set; }
          ....
    }
1

1 Answers

6
votes

I'm not familiar with this feature... but here are some suggestions:


If it's just the Window Title, then can you not just bind the activities Title like:

   this.CreateBinding().For("Title").To<FirstViewModel>(vm => vm.Title).Apply();

Is there any way to set the window's custom title as a view rather than as an id? If there is, then you could use this.BindingInflate(id) to inflate the xml before passing it to the window (no idea if that's possible - but Android - change custom title view at run time has some interesting suggestions for internal hacking...)


If the above hacking won't work, then you'll have to resort to techniques like how to set custom title bar TextView Value dynamically in android? - using that you could do something like:

   // set up your custom window here using non-binding axml with an @+id/myTitle
   Window.SetFeatureInt(WindowFeatures.CustomTitle, Resource.Layout.MainWindowTitle);

   var myTitleText = FindViewById<TextView>(Resource.Id.myTitle);
   this.CreateBinding(t).To<FirstViewModel>(vm => vm.Title).Apply();

I think that would work... although not really sure how it works across the lifetime of multiple activities - guess there may be some playing/experimentation to do.

(This question and answer - Android - change custom title view at run time - also suggests other ways to get hold of views/widgets within custom titles)