How to load jetpack compose from java activity - customdialog

How to load jetpack compose from java activity?
I have java activity:
#Override
public void onCreate(Bundle savedInstanceState) {
but on the button click I want to open #Composable function.
I'm calling it from java via
fun setContent(activity: AppCompatActivity){
activity.setContent {
CustomDialog() // contains Dialog
}
}
But this composable function destroy my previous view.
How can I open this custom dialog on the previous view?

found only such solution:
class JetPackDialog() : DialogFragment() {
override fun onCreateView(
inflater: LayoutInflater,
container: ViewGroup?,
savedInstanceState: Bundle?
): View {
return ComposeView(requireContext()).apply {
setViewCompositionStrategy(ViewCompositionStrategy.DisposeOnViewTreeLifecycleDestroyed)
setContent {
JetPackDialogView()
}
}
}
}

Related

Delegate method `WKWebView CreateWebView` method is not getting called

I am using Xamarin (C#) code for a macOS app. I have created the WKWebView and have outlet, added Navigation and UI delegates and trying to open an URL.
The Navigation delegates methods are getting called, but not sure what am I missing that UI Delegates method is not getting called.
Any help / guidance what to look for, or what mistake I am doing here, please.
Here's the code and image of same:
public override void ViewDidLoad()
{
base.ViewDidLoad();
var url = new NSUrl("https://google.com");
var request = new NSMutableUrlRequest(url);
_webView.UIDelegate = new WebViewDelegate();
_webView.NavigationDelegate = new WebViewNavigationDelegate();
_webView.LoadRequest(request);
}
}
internal class WebViewDelegate : WKUIDelegate
{
public override WKWebView CreateWebView(WKWebView webView, WKWebViewConfiguration configuration, WKNavigationAction navigationAction, WKWindowFeatures windowFeatures)
{
Console.WriteLine("this doesn't reach");
return null;
}
}
internal class WebViewNavigationDelegate : WKNavigationDelegate
{
public override void DidFinishNavigation(WKWebView webView, WKNavigation navigation)
{
Console.WriteLine("this prints");
}
}

Xamarin.Android Architecture Components: Not getting callbacks for lifecycle events

I'm trying to use the architecture components package for detecting when the application enters background or foreground state. The problem is that the callbacks are not being invoked. In the sample code below, the methods onApplicationForegrounded and onApplicationBackgrounded are not invoked:
namespace POC.Droid
{
[Application]
public class MyApp : Application, ILifecycleObserver
{
static readonly string TAG = "MyApp";
public MyApp(IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
}
public override void OnCreate()
{
base.OnCreate();
ProcessLifecycleOwner.Get().Lifecycle.AddObserver(this);
}
[Lifecycle.Event.OnStop]
public void onAppBackgrounded()
{
Log.Debug(TAG, "App entered background state.");
}
[Lifecycle.Event.OnStart]
public void onAppForegrounded()
{
Log.Debug(TAG, "App entered foreground state.");
}
}
}
My Xamarin version is 8.2.0.16 (Visual Studio Community) and Xamarin.Android.Arch.Lifecycle.Extensions version is 1.0.0. I'm using a Nougat device (7.0) for testing.
TL;DR Please annotate your lifecycle callbacks with [Export]
Here a more detailed description:
Generally, to get the methods of a lifecycle observer be invoked, please make sure that the related packages are present. Here is a part of my packages.config:
<?xml version="1.0" encoding="utf-8"?>
<packages>
<package id="Xamarin.Android.Arch.Core.Common" version="26.1.0" targetFramework="monoandroid81" />
<package id="Xamarin.Android.Arch.Core.Runtime" version="1.0.0.1" targetFramework="monoandroid81" />
<package id="Xamarin.Android.Arch.Lifecycle.Common" version="26.1.0" targetFramework="monoandroid81" />
<package id="Xamarin.Android.Arch.Lifecycle.Extensions" version="1.0.0.1" targetFramework="monoandroid81" />
<package id="Xamarin.Android.Arch.Lifecycle.Runtime" version="1.0.3.1" targetFramework="monoandroid81" />
This is how this looks in Visual Studio:
To be able to set a lifecycle observer, we need a lifecycle owner. On the application level this can be ProcessLifecycleOwner, just like the original poster showed.
Here is a slightly modified version:
using System;
using Android.App;
using Android.Arch.Lifecycle;
using Android.Util;
using Java.Interop;
namespace Stopwatch_AAC
{
[Application]
public class MyApp : Application, ILifecycleObserver
{
const string TAG = "MyApp";
public MyApp(IntPtr handle, Android.Runtime.JniHandleOwnership ownerShip) : base(handle, ownerShip)
{
}
public override void OnCreate()
{
base.OnCreate();
ProcessLifecycleOwner.Get().Lifecycle.AddObserver(this);
}
[Lifecycle.Event.OnStop]
[Export]
public void Stopped()
{
Log.Debug(TAG, "App entered background state.");
}
[Lifecycle.Event.OnStart]
[Export]
public void Started()
{
Log.Debug(TAG, "App entered foreground state.");
}
}
}
As you can see, you annotate your lifecycle methods with for example [Lifecycle.Event.OnStop]. Also, please note that you need to use [Export]. Please make sure that Mono.Android.Export is referenced in your project as shown in the following screenshot.
If you want to have lifecycle observers for an activity, I suggest to extend AppCompatActivity as it is a lifecycle owner:
using Android.App;
using Android.Arch.Lifecycle;
using Android.OS;
using Android.Support.V7.App;
using Android.Util;
using Java.Interop;
namespace Stopwatch_AAC
{
[Activity(Label = "Minimal", Exported = true, MainLauncher = true)]
public class Minimal : AppCompatActivity, ILifecycleObserver
{
const string TAG = "Stopwatch_AAC";
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
Lifecycle.AddObserver(this);
Log.Debug(TAG, Lifecycle.CurrentState.ToString());
}
[Lifecycle.Event.OnAny]
[Export]
public void Hello()
{
Log.Debug(TAG, Lifecycle.CurrentState.ToString());
}
}
}
if you need it in the activities here the events:
protected override void OnStart(){
base.OnStart();
Log.Debug(logTag, "MainActivity.OnStart() called, the activitiy is active");
}
protected override void OnPause()
{
base.OnPause();
Log.Debug(logTag, "MainActivity.OnPause() called, the activity in background");
}
protected override void OnStop()
{
base.OnStop();
Log.Debug(logTag, "MainActivity.OnStop() called, the activity is in background because of other activiy or app");
}
protected override void OnResume()
{
base.OnResume();
Log.Debug(logTag, "MainActivity.OnResume() called, the activity stated");
}
protected override void OnRestart()
{
base.OnRestart();
Log.Debug(logTag, "MainActivity.OnRestart() called, the activity is startet");
}
protected override void OnDestroy()
{
base.OnDestroy();
Log.Debug(logTag, "MainActivity.OnDestroy() called, activity is destroyed");
}
for Xamarin Forms you will find in app.xaml.cs the event which are needed for the apps.
protected override void OnStart ( ) {
// Handle when your app starts
}
protected override void OnSleep ( ) {
// Handle when your app sleeps
}
protected override void OnResume ( ) {
// Handle when your app resumes
}
I have used that package in the past, however I much prefer the implementation by James Montemagno which can be found as a nuget package called "Plugin.CurrentActivity". It creates an application class and implements the ILifecycle events for you.
From the description:
Provides a simple solution for getting access to the current Activity of the application when developing a Plugin for Xamarin.
This will lay down a base "application" class for developers in their Android application with boilerplate code to get them started.
Can be used with Android API 14+
* I am making the assumption that you're not using Xamarin.Forms. This works perfectly for a native Xamarin Android project.
Link to the Github page

MVVMCross 5.3.2 UWP: Where to Get IMvxWindowsFrame for MvxFormsUwpViewPresenter

I'm working out of the Xamarin Forms for MVVMCross 5 Solution Template and updated the packages to the latest version (5.3.2 for MVVMCross). Doing that changes some namespaces around particularly in the UWP project.
It seems that I need to resolve IMvxViewPresenter as MvxFormsUwpViewPresenter which takes a IMvxWindowsFrame as an argument. In the setup file method of Setup.cs there's a XamlControls.Frame rootFrame passed as an argument but I'm not sure if that's suppose to be cast somehow as IMvxWindowsFrame.
Where can you pull the object that implements IMvxWindowsFrame from or is there another way to turn the rootFrame into an IMvxWindowsFrame legitimately.
public class Setup : MvxFormsWindowsSetup
{
private readonly LaunchActivatedEventArgs _launchActivatedEventArgs;
public Setup(XamlControls.Frame rootFrame, LaunchActivatedEventArgs e) : base(rootFrame, e)
{
_launchActivatedEventArgs = e;
// Mvx.RegisterSingleton<IMvxWindowsFrame>(rootFrame);
}
protected override void InitializeFirstChance()
{
base.InitializeFirstChance();
Mvx.RegisterSingleton<Core.Services.ILocalizeService>(new Services.LocalizeService());
Mvx.RegisterSingleton<ISettings>(CrossSettings.Current);
Mvx.RegisterType<IMvxViewPresenter, MvxFormsUwpViewPresenter>();
}
protected override MvxFormsApplication CreateFormsApplication()
{
return new Core.FormsApp();
}
protected override IMvxApplication CreateApp()
{
return new Core.MvxApp();
}
protected override IMvxTrace CreateDebugTrace()
{
return new Core.DebugTrace();
}
}
public sealed partial class MainPage : WindowsPage
{
public MainPage()
{
this.InitializeComponent();
var start = Mvx.Resolve<IMvxAppStart>();
start.Start();
var presenter = Mvx.Resolve<IMvxViewPresenter>() as MvxFormsUwpViewPresenter;
LoadApplication(presenter.FormsApplication);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}
}
EDIT: I've been looking more into the class MvxFormsWindowsSetup in the source code at https://github.com/MvvmCross/MvvmCross/blob/develop/MvvmCross-Forms/MvvmCross.Forms.Uwp/Platform/MvxFormsWindowsSetup.cs. It appears that in the method CreateViewPresenter that the IMvxViewPresenter is registered as a singleton with the MvxWrappedFrame already inside but by default the code does not resolve when calling var presenter = Mvx.Resolve() as MvxFormsUwpViewPresenter; in the windows page. Possible bug? Trying to see if I can resolve it myself.
Looks like it fails to resolve even if I put the code right after when Mvx is suppose to register the type / singleton
protected override IMvxWindowsViewPresenter CreateViewPresenter(IMvxWindowsFrame rootFrame)
{
var presenter = new MvxFormsUwpViewPresenter(rootFrame, FormsApplication);
Mvx.RegisterSingleton<IMvxFormsViewPresenter>(presenter);
var presenter2 = Mvx.GetSingleton<IMvxViewPresenter>() as MvxFormsUwpViewPresenter;
return presenter;
}
When updating to MvvmCross 5.3.2 for UWP, the presenter needs to resolve as IMvxFormsViewPresenter rather than IMvxViewPresenter. Change the interface type and it should load properly.
public MainPage()
{
this.InitializeComponent();
var start = Mvx.Resolve<IMvxAppStart>();
start.Start();
var presenter = Mvx.Resolve<IMvxFormsViewPresenter>() as MvxFormsUwpViewPresenter;
LoadApplication(presenter.FormsApplication);
Encoding.RegisterProvider(CodePagesEncodingProvider.Instance);
}

How to tell parent to pop current modal and redirect to NavigationPage

I have a Xamarin application, where my MainPage is a navigationpage (contentpage). In this navigationpage I open modals.
In the modals I open in my MainPage, I want to use Navigation.PushAsync but this requires the NavigationPage context which a modal page is not.
I've read that the flow would be:
Tell parent/caller to pop current visible modal
Tell parent/caller
to navigate to the page I want, using Navigation.PushAsync
However, how do you do this? How do you tell the parent to do this and actually do the navigation?
I would use event handlers to get this job done:
Here is an example code:
App.cs
public class App : Application
{
public App()
{
MainPage = new NavigationPage(new PushedNavigationPage());
}
}
PushedNavigationPage Page:
public class PushedNavigationPage: ContentPage
{
public PusehdNavigationPage()
{
}
public void DoPushModalOnButtonClick()
{
var pushedModalPage = new PushedModalPage();
pushedModalPage.DoPush += HandleDoPush;
Navigation.PushModalAsync(pushedModalPage);
}
private void HandleDoPush(object sender, EventArgs e)
{
Navigation.PopModalAsync();
Navigation.PushAsync(//the page you want to push)
}
}
PushedModalPage
public class PushedModalPage : ContentPage
{
public event EventHandler DoPush;
//call this on putton click or whenever you want
private void OnDoPush()
{
if (DoPush!= null)
{
DoPush(this, EventArgs.Empty);
}
}
}
I have not awaiting the async methods but it is better to do so and this is just an example, but I think you should get the idea..

How to detect when MvxListView is bound and has loaded its bindings?

I've Inherted MvxListView to my CustomMvxListView where I dos something with the visualization when a child has been added or removed.
It works great but can be laggy when many items get bound.
Is there a way to detect when Mvx view controls are bound and loaded there first bound data?
Found a good solution myself;
To track Itemsource changes in Android in a ListView you can use a DataSetObserver.
like:
internal class MyObserver : DataSetObserver
{
private readonly object view;
public MvxListViewNonScrollableObserver(ViewToTrack view)
{
tView = view;
DoSomething():
}
public override void OnChanged()
{
base.OnChanged();
DoSomething():
}
}
Add it to a ListView by:
class MyMvxListView : MvxListView
{
protected override void OnAttachedToWindow()
{
base.OnAttachedToWindow();
itemsourceObserver = new MyObserver(this);
Adapter.RegisterDataSetObserver(itemsourceObserver);
}
protected override void OnDetachedFromWindow()
{
if (itemsourceObserver != null)
{
Adapter.UnregisterDataSetObserver(itemsourceObserver);
itemsourceObserver = null;
}
base.OnDetachedFromWindow();
}
public void DoSomething()
{
}
DoSomething() get raised after load and on every itemsource change.

Resources