Parse an actual time to TimePicker - xamarin

I'm new here so bare a bit with me. And yes i tried to google my question but really wasn't shure about the answers i found either.
So here's my problem:
I want to build an App where the User can select a Times from clicking different Buttons, and then calculate the Timedifference between.
The ButtonClick opens the TimePicker Dialog and the Examplecode i found on Microsoft Docs uses always the actual time. What i want is to use the last valid time from parsing the Buttontext. But i have no idea how to pass the ID of the senderbutton to the TimePicker class.
Here's the Eventhandler from the Button:
void TimeSelectOnClick (object sender, EventArgs eventArgs)
{
// Instantiate a TimePickerFragment (defined below)
TimePickerFragment frag = TimePickerFragment.NewInstance (
// Create and pass in a delegate that updates the Activity time display
// with the passed-in time value:
delegate (DateTime time)
{
timeSelectButton.Text = time.ToString("HH:mm");
});
// Launch the TimePicker dialog fragment (defined below):
frag.Show(FragmentManager, TimePickerFragment.TAG);
}
and here's the TimePicker dialog fragment:
// TimePicker dialog fragment
public class TimePickerFragment : DialogFragment, TimePickerDialog.IOnTimeSetListener
{
// TAG used for logging
public static readonly string TAG = "MyTimePickerFragment";
// Initialize handler to an empty delegate to prevent null reference exceptions:
Action<DateTime> timeSelectedHandler = delegate { };
// Factory method used to create a new TimePickerFragment:
public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected)
{
// Instantiate a new TimePickerFragment:
TimePickerFragment frag = new TimePickerFragment();
// Set its event handler to the passed-in delegate:
frag.timeSelectedHandler = onTimeSelected;
// Return the new TimePickerFragment:
return frag;
}
// Create and return a TimePickerDemo:
public override Dialog OnCreateDialog (Bundle savedInstanceState)
{
//Set the TimePicker default time
//Here i Want to parse the time from the button something like DateTime.Parse(buttonID.Text);
//Either with current time or parsed time... how to pass values from the sender button i have no idea
DateTime currentTime = DateTime.Parse("06:00");
// force 24-hour time format:
bool is24HourFormat = true;
// Instantiate a new TimePickerDemo, passing in the handler, the current
// time to display, and whether or not to use 24 hour format:
TimePickerDialog dialog = new TimePickerDialog
(Activity, this, currentTime.Hour, currentTime.Minute, is24HourFormat);
// Return the created TimePickerDemo:
return dialog;
}
// Called when the user sets the time in the TimePicker:
public void OnTimeSet(TimePicker view, int hourOfDay, int minute)
{
// Get the current time:
DateTime currentTime = DateTime.Now;
// Create a DateTime that contains today's date and the time selected by the user:
DateTime selectedTime = new DateTime(currentTime.Year, currentTime.Month, currentTime.Day, hourOfDay, minute, 0);
// Log the date and selected time:
Log.Debug(TAG, selectedTime.ToLongTimeString());
// Invoke the handler to update the Activity's time display to the selected time:
timeSelectedHandler (selectedTime);
}
}
thanks in advance to anybody here on Stackoverflow! You guys really do a great Job!
Cheers

You could add a property in TimePickerFragment
static string TimeString;
public static TimePickerFragment NewInstance(Action<DateTime> onTimeSelected,string time)
{
// Instantiate a new TimePickerFragment:
TimePickerFragment frag = new TimePickerFragment();
// Set its event handler to the passed-in delegate:
frag.timeSelectedHandler = onTimeSelected;
TimeString = time;
// Return the new TimePickerFragment:
return frag;
}
in Activity
TimePickerFragment frag = TimePickerFragment.NewInstance (
// Create and pass in a delegate that updates the Activity time display
// with the passed-in time value:
delegate (DateTime time)
{
timeSelectButton.Text = time.ToString("HH:mm");
},buttonID.Text);
And you can modify it in any place
TimePickerFragment.TimeString = "xxx";

Related

Multiple alerts with only one MessagingCenter subscription

I'm developing a sample where Messaging Center send status messeges not coupled from device code to my view models. At this point i used a alert message to notice the event before try in View models.
For it I used a static view instance in my share application constructor (App.xaml) where in view constructor I Subscript the status.
App (shared)
public partial class App : Application
{
#region MasterDetailPage
public static MasterDetailPage MDP;
public static NavigationPage NAV = null;
public static MainView _mainpage;
#endregion
public App ()
{
InitializeComponent();
NAV = new NavigationPage(new StarterView()) { BarBackgroundColor = Color.FromHex("701424"), BarTextColor = Color.White }; ;
MDP = new MasterDetailPage();
MDP.BackgroundColor = Xamarin.Forms.Color.FromHex("701424");
_mainpage = new MainView();
MDP.Master = _mainpage;
MDP.Detail = NAV;
MainPage = MDP;
MainPage.Title = "H2X";
}
(View shared)
public MainView ()
{
InitializeComponent ();
string a="Test";
#region MessegeCenter
MessagingCenter.Subscribe<string,string>("APP", "Message_Received", async (sender,arg) =>
{
string b = a;
a = $"{arg}";
await DisplayAlert("Atenção", a+b, "Ok");
});
#endregion
}
Into the specific platform code (Device - UWP) I create a timer that sends messages after some time instanced in mainpage constructor.
void dispatcherTimer_Tick(object sender, object e)
{
DateTimeOffset time = DateTimeOffset.Now;
TimeSpan span = time - lastTime;
lastTime = time;
//Time since last tick should be very very close to Interval
TimerLog.Text += timesTicked + "\t time since last tick: " + span.ToString() + "\n";
timesTicked++;
if (timesTicked > timesToTick)
{
MessagingCenter.Send<string,string>("APP","Message_Received","MR");
}
}
When I run it, twice alert messages with the same text are opening, but there aren't two subscriptions. The same text give me the information that it was from the same send event.
Where is the problem ? Is there any relationship with my static view ?
Thank you in advance
Guilherme
It is a good practice to always unsubscribe from the MessagingCenter.
MessagingCenter.Unsubscribe<string, string>(this, "Message_Received");
If MessagingCenter is subscribed twice ,then functions will be call twice.

Xamarin Forms : Add ItemSource on focus

Am trying to load ItemSource of a picker when the picker is focused.
But the data is not loaded on 1st focus.
here is the code sample
List<object> itmSrc;
Picker picker = new Picker();
itmSrc = Controls[i].ItemSource;
picker.Focused += BindItemSourceOnFocus;
public void BindItemSourceOnFocus(object sender, FocusEventArgs e)
{
var p = e.VisualElement as Picker;
p.ItemsSource = itmSrc;
}
If any other different approach is possible, let me know.
You can do it adding items on an async method, or another thread. Load the data on view focus is just transferring the issue to another place, and it gives a bad user experience at all.
If you run a code block inside a Task.Run(), for example, this code will be executed on another thread, and the interface should not hang on data loading.
Something like this:
public class MyPage : ContentPage
{
List<object> itmSrc;
Picker picker;
public MyPage()
{
// Your stuff goes here
itmSrc = new List<object>();
picker = new Picker();
StackLayout content = new StackLayout();
content.Crindren.Add(picker);
this.Content = content;
Task.Run(() => LoadData());
}
private void LoadData()
{
// Get your data from anywhere and put it on the itemSrc from here.
// Then...
picker.ItemsSource = itmSrc;
}
}
I hope it helps.

VSTO How to hide FormRegion in Reply email [in InlineResponse also]?

So, as the subject says...what is the easiest way to hide FormRegion if email is in Reply mode whether its in a new window or with InlineResponse?
Just set the FormRegion.Visible property which returns a Boolean value that indicates whether the form region is visible or hidden.
Went back to test the approach in my answer after the question from #EugeneAstafiev and -- of course -- this was more complicated than I first thought... but I did get it working with some additional code.
The issue is that when the user clicks "Reply", it opens a new inspector window with a new instance of the FormRegion. So setting the Visible property to false in the event handler sets it only on the current "Read" mode inspector window -- rather than the new "Compose" mode inspector window that gets opened. So, instead the code samples below set up a bool flag property in ThisAddIn called LoadFormRegion that can be toggled to "false" when the Reply or ReplyAll event is fired.
Also, I noticed that setting Visible to false on the FormRegion still draws the area of the FormRegion on the inspector window, just with nothing in it. To completely prevent the FormRegion from loading, you can test for "Compose" mode and then the ThisAddin.LoadFormRegion flag in the FormRegionInitializing event handler located inside of the "Form Region Factory" at the top of the code page -- which is usually folded away from view. In that code block, setting "e.Cancel = true" will prevent the FormRegion from loading at all.
Here is the revised code for the FormRegion, which now subscribes to all three email button click events (Reply, ReplyAll, Forward), and sets the ThisAddIn.LoadFormRegion flag accordingly:
namespace TESTINGOutlookAddInVSTO
{
partial class FormRegion1
{
#region Form Region Factory
[Microsoft.Office.Tools.Outlook.FormRegionMessageClass(Microsoft.Office.Tools.Outlook.FormRegionMessageClassAttribute.Note)]
[Microsoft.Office.Tools.Outlook.FormRegionName("TESTINGOutlookAddInVSTO.FormRegion1")]
public partial class FormRegion1Factory
{
// Occurs before the form region is initialized.
// To prevent the form region from appearing, set e.Cancel to true.
// Use e.OutlookItem to get a reference to the current Outlook item.
private void FormRegion1Factory_FormRegionInitializing(object sender, Microsoft.Office.Tools.Outlook.FormRegionInitializingEventArgs e)
{
if (e.FormRegionMode == Outlook.OlFormRegionMode.olFormRegionCompose)
{
var myAddIn = Globals.ThisAddIn;
if (myAddIn.LoadFormRegion == false)
{
e.Cancel = true;
}
}
}
}
#endregion
// Occurs before the form region is displayed.
// Use this.OutlookItem to get a reference to the current Outlook item.
// Use this.OutlookFormRegion to get a reference to the form region.
private void FormRegion1_FormRegionShowing(object sender, System.EventArgs e)
{
// Reset ThisAddIn.LoadFormRegion flag to true (in case user starts
// composing email from scratch without clicking Reply, ReplyAll or Forward)
var myAddin = Globals.ThisAddIn;
myAddin.LoadFormRegion = true;
var myMailItem = this.OutlookItem as Outlook.MailItem;
// Track these events to set the ThisAddIn.FormRegionShowing flag
((Outlook.ItemEvents_10_Event)myMailItem).Reply += myMailItem_Reply;
((Outlook.ItemEvents_10_Event)myMailItem).ReplyAll += myMailItem_ReplyAll;
((Outlook.ItemEvents_10_Event)myMailItem).Forward += myMailItem_Forward;
}
// Sets FormRegionShowing flag on ThisAddin
private void SetFormRegionShowing(bool show)
{
var myAddIn = Globals.ThisAddIn;
myAddIn.LoadFormRegion = show;
}
private void myMailItem_Forward(object Forward, ref bool Cancel)
{
SetFormRegionShowing(true);
}
private void myMailItem_ReplyAll(object Response, ref bool Cancel)
{
SetFormRegionShowing(false);
}
private void myMailItem_Reply(object Response, ref bool Cancel)
{
SetFormRegionShowing(false);
}
// Occurs when the form region is closed.
// Use this.OutlookItem to get a reference to the current Outlook item.
// Use this.OutlookFormRegion to get a reference to the form region.
private void FormRegion1_FormRegionClosed(object sender, System.EventArgs e)
{
}
}
}
And here's the new code for ThisAddIn to setup the LoadFormRegion property flag:
namespace TESTINGOutlookAddInVSTO
{
public partial class ThisAddIn
{
private bool loadFormRegion;
public bool LoadFormRegion { get => loadFormRegion; set => loadFormRegion = value; }
private void ThisAddIn_Startup(object sender, System.EventArgs e)
{
LoadFormRegion = true;
}
private void ThisAddIn_Shutdown(object sender, System.EventArgs e)
{
// Note: Outlook no longer raises this event. If you have code that
// must run when Outlook shuts down, see https://go.microsoft.com/fwlink/?LinkId=506785
}
#region VSTO generated code
/// <summary>
/// Required method for Designer support - do not modify
/// the contents of this method with the code editor.
/// </summary>
private void InternalStartup()
{
this.Startup += new System.EventHandler(ThisAddIn_Startup);
this.Shutdown += new System.EventHandler(ThisAddIn_Shutdown);
}
#endregion
}
}
Tested the above and works nearly perfectly... I noticed that if there is a "Draft" reply in the user's Inbox created before the add-in was loaded, clicking on that email to continue editing in the Preview window or a new inspector window will cause some wonky display issues with the FormRegion. However, once I closed out that draft, then everything seemed to return to normal.

can someone tell me how to change specific color to a caldroid calendar

I'm working on an islamic app that show hijri calendar and also applying events like adding a specific date, time, event title and subject of that date so I want that when the app starts and displays calendar then the events' dates have different color.
caldroidFragment.setCaldroidListener(new CaldroidListener() {
#SuppressWarnings("deprecation")
#Override
public void onSelectDate(Date date, View view) {
// TODO Auto-generated method stub
// caldroidFragment.setSelectedDates(date, date);
Calendar text=Calendar.getInstance();
text.clear();
// text.set(Calendar.);
int d=(int) date.getDate();
int m=(int) date.getMonth();
int y=(int) date.getYear();
text.set(Calendar.YEAR, y+1900);
text.set(Calendar.MONTH, m);
text.set(Calendar.DATE, d);
hijridate.setText(HijriCalendarDate.getSimpleDate(text, 0));
}
}
enter link description here
You should use setBackgroundDrawableForDates method of caldroid object and pass the map with dates as keys and Drawable as value. Something like this:
import android.graphics.drawable.ColorDrawable;
final Map<Date, Drawable> backgroundForDateMap = new HashMap<>();
final Calendar c = Calendar.getInstance();
// 1. date
c.set(2016, Calendar.MAY, 1);
backgroundForDateMap.put(c.getTime(), new ColorDrawable(Color.GREEN));
// 2. date
c.set(2016, Calendar.MAY, 2);
backgroundForDateMap.put(c.getTime(), new ColorDrawable(Color.YELLOW));
caldroidFragment.setBackgroundDrawableForDates(backgroundForDateMap);

MVVM - View loading and eventhandling

In my windows phone app, I need to track some events to get a good flow. But I'm not sure how to handle them in good sequence.
What needs to be done at startup of the app:
Main view is loaded and corresponding view model instantiated
In the constructor of the view model I initiate a login sequence that signals when completed with an eventhandler
Now when the login sequence has finished AND the view is completely loaded I need to startup another sequence.
But here is the problem, the order of these 2 events 'completing' is not always the same...
I've use the EventToCommand from MVVMLight to signal the view model that the view has 'loaded'.
Any thoughts on how to synchronize this.
As you should not use wait handles or something similar on the UI thread. You will have to sync the two method using flags in your view model and check them before progressing.
So, implement two boolean properties in your view model. Now when the login dialog is finished set one of the properties (lets call it IsLoggedIn) to true, and when the initialization sequence is finished you set the other property (how about IsInitialized) to true. The trick now lies in the implementation of the setter of these two properties:
#region [IsInitialized]
public const string IsInitializedPropertyName = "IsInitialized";
private bool _isInitialized = false;
public bool IsInitialized {
get {
return _isInitialized;
}
set {
if (_isInitialized == value)
return;
var oldValue = _isInitialized;
_isInitialized = value;
RaisePropertyChanged(IsInitializedPropertyName);
InitializationComplete();
}
}
#endregion
#region [IsLoggedIn]
public const string IsLoggedInPropertyName = "IsLoggedIn";
private bool _isLoggedIn = false;
public bool IsLoggedIn {
get {
return _isLoggedIn;
}
set {
if (_isLoggedIn == value)
return;
var oldValue = _isLoggedIn;
_isLoggedIn = value;
RaisePropertyChanged(IsLoggedInPropertyName);
InitializationComplete();
}
}
#endregion
public void InitializationComplete() {
if (!(this.IsInitialized && this.IsLoggedIn))
return;
// put your code here
}
Alternatively you can remove the InitializationComplete from the setters and change InitializationComplete to:
public void InitializationComplete() {
// put your code here
}
Then subscribe to the 'PropertyChanged' event use the following implementation:
private void Class1_PropertyChanged(object sender, System.ComponentModel.PropertyChangedEventArgs e) {
if (e.PropertyName == IsInitializedPropertyName || e.PropertyName == IsLoggedInPropertyName) {
if (this.IsInitialized && this.IsLoggedIn)
InitializationComplete();
}
}

Resources