Xamarin.Android , OnBackPressed() method handling - xamarin.android

I have main_activity and dashboard_activity, on dashboard_activity I added fragment using code in OnBackPressed() method
public override void OnBackPressed()
{
//base.OnBackPressed();
FragmentTransaction transaction =FragmentManager.BeginTransaction();
Dialog dialog = new Dialog();
dialog.Show(transaction,"dialog_fragment");
}
My fragment code is here
class Dialog:DialogFragment
{
private Button btnExitapp;
private Button btnLogOut;
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
base.OnCreateView(inflater, container, savedInstanceState);
var view = inflater.Inflate(Resource.Layout.dialog, container,false);
btnExitapp=view.FindViewById<Button>(Resource.Id.btnExitapp);
btnExitapp.Click += BtnExitapp_Click;
btnLogOut = view.FindViewById<Button>(Resource.Id.btnLogOut);
btnLogOut.Click += BtnLogOut_Click;
return view;
}
private void BtnLogOut1_Click(object sender, EventArgs e)
{
}
private void BtnExitapp1_Click(object sender, EventArgs e)
{
System.Diagnostics.Process.GetCurrentProcess().Kill();
}
}
Note:My code for btnExitapp work fine only once after deployment and if I reopen the app in emulator and press btnExit it close app and reopen with Dashboard_Activity instead of closing app.
Please guide me to achieve
that when BtnLogout pressed, should go back to Main_Activity as it work on backpress button and when BtnExitapp pressed should close the app

At first, if you want to go back to the previous activity in your dialogframent, you can try to call the base.OnBackPressed(); in the private void BtnLogOut1_Click(object sender, EventArgs e). In addition, maybe you need to call it twice, from dialog to dashborad activity and then the main activity.
Then if you want to exit the app, you can use the following code:
private void BtnExitapp1_Click(object sender, EventArgs e)
{
Android.OS.Process.KillProcess(Android.OS.Process.MyPid());
}

Related

show a login page before moving to main app in xamarin.android

so I'm trying to make an android app that starts with a login page (that I thought could be a dialog fragment) and if the user's credentials are correct, then he'll be directed to the main app that is supposed to be a navigation drawer app. I tried to use the dialog fragment but I didn't know how to set it to appear at the very beginning. what should I do?
You should create a Activity as a MainLauncher, Activity you can use a blank Layout.xml like following code, then pop a DialogFragment like following code. Note: you should add MainLauncher = true,NoHistory =true in your Activity attribute. NoHistory =true will make the back button navigate to the desktop.
namespace App2
{
[Activity(Label = "LoginActivity", Theme = "#style/AppTheme.NoActionBar",MainLauncher = true,NoHistory =true)]
public class LoginActivity : AppCompatActivity, OnLoginInforCompleted
{
public void inputLoginInforCompleted(string userName, string passWord)
{
//You can get the username and password here
StartActivity(new Intent(this,typeof(MainActivity)));
}
protected override void OnCreate(Bundle savedInstanceState)
{
base.OnCreate(savedInstanceState);
SetContentView(Resource.Layout.LoginLayout);
MyDialogFragment dialogFragment = new MyDialogFragment();
dialogFragment.setOnLoginInforCompleted(this);
dialogFragment.Cancelable = false;
var SupportFragmentManager = this.FragmentManager;
dialogFragment.Show(SupportFragmentManager, "dialog");
}
}
}
I achieve the a callback interface OnLoginInforCompleted, If User click the Login Button, will navigate to the navigation drawer page.
public interface OnLoginInforCompleted
{
void inputLoginInforCompleted(String userName, String passWord);
}
Here is code about MyDialogFragment .
public class MyDialogFragment : DialogFragment
{
public override View OnCreateView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState)
{
View view = inflater.Inflate(Resource.Layout.layout3, container, false);
Button button = view.FindViewById<Button>(Resource.Id.button1);
EditText MyeditText1 = view.FindViewById<EditText>(Resource.Id.editText1);
EditText MyeditText2 = view.FindViewById<EditText>(Resource.Id.editText2);
button.Click += delegate {
//set the data to the loginpage
mOnLoginInforCompleted.inputLoginInforCompleted(MyeditText1.Text.ToString(), MyeditText2.Text.ToString());
Dismiss();
};
return view;
}
//set for Callback
private OnLoginInforCompleted mOnLoginInforCompleted;
public void setOnLoginInforCompleted(OnLoginInforCompleted onLoginInforCompleted)
{
mOnLoginInforCompleted = onLoginInforCompleted;
}
public override Dialog OnCreateDialog(Bundle savedInstanceState)
{
return base.OnCreateDialog(savedInstanceState);
}
}
Here is running GIF.
Here is my demo, you can refer to it.
https://github.com/851265601/Xamarin.Android_ListviewSelect/blob/master/App2.zip

How to keep loading sign active until page loads completing.Page comes later after ProgressDialog loading sign stops at xamarin native android

My page load later after ProgressDialog loading sign stops. Inside my page images list view are loading via GetImageBitmapFromUrl. Can u pls suggest how can I keep loading sign on until my page loads properly....
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
var mDialog = new ProgressDialog(this.Context);
mDialog.SetMessage("Please wait...");
mDialog.SetCancelable(false);
mDialog.Show();
_data = (await ServiceContext.Current.Duas.GetAll()).ToList();
DuasAdapter adapter = new DuasAdapter(this.Context, _data);
_lstDuas.Adapter = adapter;
_lstDuas.ItemClick += LstDuas_ItemClick;
mDialog.Cancel();
}
From shared code , the reason why not waitting for data loaded may be the follow line :
_data = (await ServiceContext.Current.Duas.GetAll()).ToList();
You need to check whehter ServiceContext.Current.Duas.GetAll() also contains the await method . If no , there will no wait to invoke the next line code .
I will show the sample code here , TaskMethod can be looked as LoadDataMethod .
if code as follow :
private async void Button_Clicked(object sender, EventArgs e)
{
Console.WriteLine("Start code");
int codeResult = await TaskMethod();
Console.WriteLine("End code :" + codeResult);
}
private async Task<int> TaskMethod()
{
Task.Delay(3000);
return 1;
}
When I clicked the Button , you will see the result is :
01-10 14:14:48.474 I/mono-stdout( 5920): Start code
01-10 14:14:48.510 I/mono-stdout( 5920): End code :1
You will see no wait , then End code . The task has not finished .
If code as follow , you will see as your expected .
private async void Button_Clicked(object sender, EventArgs e)
{
Console.WriteLine("Start code");
int codeResult = await TaskMethod();
Console.WriteLine("End code :" + codeResult);
}
private async Task<int> TaskMethod()
{
await Task.Delay(3000);
return 1;
}
The result is :
01-10 14:19:59.396 I/mono-stdout( 6040): Start code
01-10 14:20:02.455 I/mono-stdout( 6040): End code :1
Now the Code end until Task finished .
hi I have solved by modifying my code below...
public override async void OnActivityCreated(Bundle savedInstanceState)
{
base.OnActivityCreated(savedInstanceState);
var mDialog = new ProgressDialog(this.Context);
mDialog.SetMessage("Please wait...");
mDialog.SetCancelable(false);
mDialog.Show();
_vdos = (await ServiceContext.Current.IslamicVdo.GetAll()).ToList();
VdoAdapter adapter = new VdoAdapter(this.Context, _vdos);
_lstVdo.Adapter = adapter;
fragsIDActivity.RunOnUiThread(() => mDialog.Hide());
}

Need to print UWP MapControl with route results

I have a MapControl working just creating my route. Now, I just need to figure out a way to print it out. Using the UWP printing sample, I get a black box where the control should be. The map and route are being built, just not rendered correctly in the print preview. I thought I saw a MapControl.Print... but I think that was in the Bing.Maps stuff. Any pointers would be appreciated. Thanks.
Using the UWP printing sample, I get a black box where the control should be.
It seems the MapControl can not be printed.
As a workround, we can use RenderTargetBitmap to get the image from the MapControl. That we can print the image.
Using a RenderTargetBitmap, you can accomplish scenarios such as applying image effects to a visual that originally came from a XAML UI composition, generating thumbnail images of child pages for a navigation system, or enabling the user to save parts of the UI as an image source and then share that image with other apps.
Because RenderTargetBitmap is a subclass of ImageSource, it can be used as the image source for Image elements or an ImageBrush brush.
For more info,see RenderTargetBitmap.
For example:
RenderTargetBitmap renderTargetBitmap = new RenderTargetBitmap();
await renderTargetBitmap.RenderAsync(MyMap);
MyImage.Source = renderTargetBitmap;
The printing code:
public sealed partial class MainPage : Page
{
private PrintManager printmgr = PrintManager.GetForCurrentView();
private PrintDocument printDoc = null;
private PrintTask task = null;
public MainPage()
{
this.InitializeComponent();
printmgr.PrintTaskRequested += Printmgr_PrintTaskRequested;
}
private void Printmgr_PrintTaskRequested(PrintManager sender, PrintTaskRequestedEventArgs args)
{
var deferral = args.Request.GetDeferral();
task = args.Request.CreatePrintTask("Print", OnPrintTaskSourceRequrested);
task.Completed += PrintTask_Completed;
deferral.Complete();
}
private void PrintTask_Completed(PrintTask sender, PrintTaskCompletedEventArgs args)
{
//the PrintTask is completed
}
private async void OnPrintTaskSourceRequrested(PrintTaskSourceRequestedArgs args)
{
var def = args.GetDeferral();
await Dispatcher.RunAsync(Windows.UI.Core.CoreDispatcherPriority.Normal,
() =>
{
args.SetSource(printDoc?.DocumentSource);
});
def.Complete();
}
private async void appbar_Printer_Click(object sender, RoutedEventArgs e)
{
if (printDoc != null)
{
printDoc.GetPreviewPage -= OnGetPreviewPage;
printDoc.Paginate -= PrintDic_Paginate;
printDoc.AddPages -= PrintDic_AddPages;
}
this.printDoc = new PrintDocument();
printDoc.GetPreviewPage += OnGetPreviewPage;
printDoc.Paginate += PrintDic_Paginate;
printDoc.AddPages += PrintDic_AddPages;
bool showPrint = await PrintManager.ShowPrintUIAsync();
}
private void PrintDic_AddPages(object sender, AddPagesEventArgs e)
{
printDoc.AddPage(this);
printDoc.AddPagesComplete();
}
private void PrintDic_Paginate(object sender, PaginateEventArgs e)
{
PrintTaskOptions opt = task.Options;
printDoc.SetPreviewPageCount(1, PreviewPageCountType.Final);
}
private void OnGetPreviewPage(object sender, GetPreviewPageEventArgs e)
{
printDoc.SetPreviewPage(e.PageNumber, this);
}
}

Detecting when a template was loaded in wpf

I am working with an attached behavior for logging user actions on a ScrollBar.
my code:
class ScrollBarLogBehavior : Behavior<ScrollBar>
{
protected override void OnAttached()
{
base.OnAttached();
AssociatedObject.Loaded += new RoutedEventHandler(AssociatedObject_Loaded);
}
void AssociatedObject_Loaded(object sender, RoutedEventArgs e)
{
...
var track = (Track)AssociatedObject.Template.FindName("PART_Track", AssociatedObject);
// ** HERE is the problem: track is null ! **
...
}
How can I detect that the template has loaded and I can find the Track?
(when I call AssociatedObject.Template.LoadContent() the result containt the requested Track, so it i a matter of timing and not a matter of wrong template or naming)
Override the method OnApplyTemplate
public override void OnApplyTemplate()
{
base.OnApplyTemplate();
var textBox = Template.FindName("PART_Textbox", this) as TextBox;
}
I did not find any good way to detect when the template was loaded. However, I did find a way to find the Track:
in OnAttached() - register to Scroll event fo the ScrollBar (this can only happen after the entire template is loaded, of course):
protected override void OnAttached()
{
base.OnAttached();
_scrollHandler = new ScrollEventHandler(AssociatedObject_Scroll);
AssociatedObject.AddHandler(ScrollBar.ScrollEvent, _scrollHandler, true);
}
When handling the Scroll event, remove registration and find the Thumb:
void AssociatedObject_Scroll(object sender, ScrollEventArgs e)
{
var track = (Track)AssociatedObject.Template.FindName("PART_Track", Associated
if (track == null)
return;
AssociatedObject.RemoveHandler(ScrollBar.ScrollEvent, _scrollHandler);
// do my work with Track
...
}
If I understand correctly, you wish to create an attached behavior that will reference a template part after the ScrollBar has been loaded.
The following should work:
internal static class ScrollBarLogBehavior
{
public static readonly DependencyProperty LogUserActionProperty = DependencyProperty.RegisterAttached(
"LogUserAction",
typeof(bool),
typeof(ScrollBarLogBehavior),
new UIPropertyMetadata(default(bool), LogUserActionChanged));
public static bool GetLogUserAction(DependencyObject obj)
{
return (bool)obj.GetValue(LogUserActionProperty);
}
public static void SetLogUserAction(DependencyObject obj, bool value)
{
obj.SetValue(LogUserActionProperty, value);
}
public static void LogUserActionChanged(DependencyObject s, DependencyPropertyChangedEventArgs e)
{
if (s is ScrollBar scrollBar)
{
scrollBar.Loaded += OnScrollBarLoaded;
}
}
private static void OnScrollBarLoaded(object sender, RoutedEventArgs e)
{
if (sender is ScrollBar scrollBar)
{
if (scrollBar.Template != null)
{
// I'm not sure, but the `name` in the following method call might be case sensitive.
if (scrollBar.Template.FindName("PART_Track", scrollBar) is Track track)
{
// do work with `track` here
}
}
}
}
}
where you would "attach" the behavior in your XAML with:
<ScrollBar guiControls:ScrollBarLogBehavior.LogUserAction="True">
<!-- more here -->
</ScrollBar>
BE ADVISED: this implementation completely ignores the bool value that is being set for LogUserAction

Problem with SaveFileDialog in Silverlight 3

i have weird exception by SaveFileDialog in Silverlight 3. I don't really have a idea where the problem is.
I create instance of SaveFileDialog in Loaded event of user control. After Download button is clicked and dialogResult is true asynchronous file download is started. After file download is completed, method OpenFile() is called. This works fine once, but second time I get exception:
Exception message:
"No file was selected"
Details:
{System.InvalidOperationException: No file was selected.
at System.Windows.Controls.SaveFileDialog.OpenFile()
at Spaces.Client.Views.Dialogs.FileDialog.BL_DownloadFileCompleted(Object sender, EventArguments`1 e)
at Spaces.Client.BL.Interface.DownloadFileCompletedEventHandler.Invoke(Object sender, EventArguments`1 e)
at Spaces.Client.BL.WebService.SpacesService._spacesService_DownloadFileCompleted(Object sender, DownloadFileCompletedEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Spaces.Client.BL.SpacesServiceReference.ServiceClient.OnDownloadFileCompleted(Object state)}
Stack:
at System.Windows.Controls.SaveFileDialog.OpenFile()
at Spaces.Client.Views.Dialogs.FileDialog.BL_DownloadFileCompleted(Object sender, EventArguments`1 e)
at Spaces.Client.BL.Interface.DownloadFileCompletedEventHandler.Invoke(Object sender, EventArguments`1 e)
at Spaces.Client.BL.WebService.SpacesService._spacesService_DownloadFileCompleted(Object sender, DownloadFileCompletedEventArgs e)
at System.EventHandler`1.Invoke(Object sender, TEventArgs e)
at Spaces.Client.BL.SpacesServiceReference.ServiceClient.OnDownloadFileCompleted(Object state)
Here code snippet:
private void _userControlFileDialog_Loaded(object sender, RoutedEventArgs e)
{
_comboBoxVersions.ItemsSource = _file.Versions;
if (_comboBoxVersions.Items.Count > 0)
_comboBoxVersions.SelectedIndex = 0;
String extension = "*." + _file.Extension;
_sfd = new SaveFileDialog();
_sfd.DefaultExt = _file.Extension;
_sfd.Filter = extension + "|" + extension;
}
private void _hyperlinkButtonDownload_Click(object sender, RoutedEventArgs e)
{
string path = ((FileVersion)_comboBoxVersions.SelectedItem).Url;
bool? dialogResult = _sfd.ShowDialog();
if (dialogResult == true)
{
AppContext.BL.DownloadFileCompleted += new Spaces.Client.BL.Interface.DownloadFileCompletedEventHandler(BL_DownloadFileCompleted);
AppContext.BL.DownloadFileAsync(AppContext.AuthenticatedUser, path);
}
}
void BL_DownloadFileCompleted(object sender, Spaces.Client.BL.Interface.EventArguments<byte[]> e)
{
byte [] data = e._result;
using (Stream fileStream = (Stream)_sfd.OpenFile())
{
fileStream.Write(data, 0, data.Length);
fileStream.Flush();
fileStream.Close();
}
}
Have anybody idea what is wrong?
Regards
Anton Kalcik
There was problem with multiple event handlers. On each click is event handler attached and never detached. Event handler stays attached also after UserControl is closed. So it is on developer to detach event handler on properly way.
Regards
AKa

Resources